WenHao
WenHao

Reputation: 1235

Sitecore: Exclude items during lucene search

How can I use ADC during lucene search to exclude out unwanted items? (Given that I have few millions of items) Given the unwanted items are different from time to time, thus, it is impossible for me to use the config file to exclude it out.

Upvotes: 2

Views: 1736

Answers (2)

mmmeff
mmmeff

Reputation: 1033

Below is a pretty extensive overview of what you'll need to do to get this going. What it does is it prevents items that have a checkbox field checked in sitecore from ever even getting indexed. Sorry it's not easier!

Requirements: Advanced Database Crawler: http://marketplace.sitecore.net/en/Modules/Search_Contrib.aspx

1) Add a checkbox field to the base template in sitecore, titled "Exclude from Search" or whatever.

2) Create your custom index crawler that will index the new field.

namespace YourNamespace
{
    class MyIndexCrawler : Sitecore.SharedSource.SearchCrawler.Crawlers.AdvancedDatabaseCrawler
    {
        protected override void AddSpecialFields(Lucene.Net.Documents.Document document, Sitecore.Data.Items.Item item)
        {
            base.AddSpecialFields(document, item);

            document.Add(CreateValueField("exclude from search",
                string.IsNullOrEmpty(item["Exclude From Search"]) 
                ? "0" 
                : "1"));

3) Configure Lucene to use a new custom index crawler (Web.config if you're not using includes)

<configuration>
  <indexes hint="list:AddIndex">
    ...
    <locations hint="list:AddCrawler">
      <master type="YourNameSpace.MyIndexCrawler,YourNameSpace">
        <Database>web</Database>
        <Root>/sitecore/content</Root>
        <IndexAllFields>true</IndexAllFields>

4) Configure your search query

var excludeQuery = new BooleanQuery();
Query exclude = new TermQuery(new Term("exclude from search", "0"));
excludeQuery.Add(exclude, BooleanClause.Occur.MUST);

5) Get your search hits

var db = Sitecore.Context.Database;
var index = SearchManager.GetIndex("name_of_your_index"); // I use db.Name.ToLower() for my master/web indexes
var context = index.CreateSearchContext();
var searchContext = new SearchContext(db.GetItem(rootItem));

var hits = context.Search(excludeQuery, searchContext);

Note: You can obviously use a combined query here to get more flexibility on your searches!

Upvotes: 3

Marek Musielak
Marek Musielak

Reputation: 27132

From what I understand you want to be able to manually set some of the items as excluded from appearing in search results.

The simplest solution would be to add some Exclude boolean flag to the base template and check for this flag while searching for the items.

The other solution is to create some settings page with multilist field for items excluded in the search and then pass ids of the selected items to the search query excluding them from the search.

Upvotes: 4

Related Questions