1
votes

I am performing a search in which I have to get the 'ID' (field) of the last item stored in the sitecore/content/data/MyItem. The items stored in this folder are in 1000+ in number. I know Lucene search is by far efficient. I performed a Lucene Search to get the items based on the value like this:

using (IndexSearchContext searchContext = indx.CreateSearchContext())
            {
                var db = Sitecore.Context.Database;
                CombinedQuery query = new CombinedQuery();

                QueryBase catQuery = new FieldQuery("country", guidValueToSearch); //FieldName, FieldValue.
                SearchHits results = searchContext.Search(catQuery); //Searching the content items by fields.
                SearchResultCollection result = results.FetchResults(0, numOfArticles);

Here I am passing the guidValueToSearch for the items needs to be fetched for "country" field value. But I want to get the last item in the folder. How should I achieve this?

2
What do you mean by last item in the tree(sort order) or the last updated item? - marto
Do you mean within that folder in the content tree, retrieve the most recently updated item? - Mark Ursino

2 Answers

4
votes

If you know you need the last childitem of /sitecore/content/data/MyItem, you could also use a more simple approach and get the parentItem and then retrieve the last child:

Item myItem = Sitecore.Context.Database.GetItem("/sitecore/content/data/MyItem");
Item lastItem = myItem.Children.Last();

The same could be done with Descendants instead of Children.

1
votes

If you did want to implement it using search then have a look at this answer which explains how to extend the IndexSearchContext to have methods that accept a Lucene.Net.Search.Sort. You can then pass in the Sitecore.Search.BuiltinFields.Created or Sitecore.Search.BuiltinFields.Updated field (depending on what you are after).