Search code examples
searchsitecoresitecore7bucketsitecore7.5

Sitecore HOWTO: Search item bucket for items with specific values


I have an item bucket with more then 30 000 items inside. What I need is to quickly search items that have particular field set to particular value, or even better is to make something like SELECT WHERE fieldValue IN (1,2,3,4) statement. Are there any ready solutions? I searched the web and the only thing I found is "Developer's Guide to Item Buckets and Search" but there is no code examples.


Solution

  • Using Sitecore Content Editor:

    Go to the bucket item then In search tab, start typing the following (replace fieldname and value with actual field name and value):

    custom:fieldname|value

    Then hit enter, you see the result of the query, you can multiple queries at once if you want.

    Using Sitecore Content Search API:

    using Sitecore.ContentSearch;
    using Sitecore.ContentSearch.Linq;
    using Sitecore.ContentSearch.SearchTypes;
    using Sitecore.ContentSearch.Linq.Utilities
    
    ID bucketItemID = "GUID of your bucket item";
    ID templateID = "Guid of your item's template under bucket";
    string values = "1,2,3,4,5";
    
    using (var context = ContentSearchManager.GetIndex("sitecore_web_index").CreateSearchContext())
    {
        var predicate = PredicateBuilder.True<SearchResultItem>();
        predicate = PredicateBuilder.And(item => item.TemplateId == new ID(templateID) 
                                         && item.Paths.Contains(bucketItemID));
        var innerPredicate = PredicateBuilder.False<SearchResultItem>();
        foreach(string val in values.Split(','))
        {
             innerPredicate = PredicateBuilder.False<SearchResultItem>();
             innerPredicate = innerPredicate.Or(item => item["FIELDNAME"] == val);
        }
        predicate = predicate.And(innerPredicate);
    
        var result = predicate.GetResults();
        List<Item> ResultsItems = new List<Item>();
        foreach (var hit in result.Hits)
        {
           Item item = hit.Document.GetItem();
           if(item !=null)
           {
              ResultsItems .Add(item);
           }
        }
    }
    

    The following links can give good start with the Search API:

    1. http://www.fusionworkshop.co.uk/news-and-insight/tech-lab/sitecore-7-search-a-quickstart-guide#.VPw8AC4kWnI
    2. https://www.sitecore.net/learn/blogs/technical-blogs/sitecore-7-development-team/posts/2013/06/sitecore-7-poco-explained.aspx
    3. https://www.sitecore.net/learn/blogs/technical-blogs/sitecore-7-development-team/posts/2013/05/sitecore-7-predicate-builder.aspx

    Hope this helps!