I am trying to setup a very basic search index, to index all items in a specific folder. but I'm fail to do it. Please, check my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sitecore.Data.Items;
using Sitecore.ContentSearch;
using Sitecore.Search;
using Sitecore.ContentSearch.SearchTypes;
using Sitecore.ContentSearch.Linq;
using Sitecore.Data;
protected void Page_Load(object sender, EventArgs e)
{
var Index = ContentSearchManager.GetIndex("sitecore_web_index");
using (var Context = Index.CreateSearchContext())
{
IQueryable<SearchResultItem> query =
Context.GetQueryable<SearchResultItem>()
.Where(x => x.TemplateName.Contains("main"));
SearchResults<SearchResultItem> results = query.GetResults();
if (results.Hits.Any())
{
rpNewsListing.DataSource =
results.Hits.Select(hit => hit.Document.GetItem());
rpNewsListing.DataBind();
//rpNewsListing.DataSource = results.Hits.Select(x => x.Document);
// Extract the Document for each hit - this is the NewsResult object
//rpNewsListing.DataBind();
}
}
}
Is this right? I just want to create a simple index, and then start using it.
With the default indexes Sitecore provides, it is not necessary to create a custom index yourself, unless you have very specific needs. The default indexes contain everything from your Sitecore tree. A custom index needs to be configured in the config files, however, you can extend the existing default indexes with custom fields if you like.
The code you provide is correct in getting search results from the standard Sitecore indexes.
I suppose you are using the statment
TemplateName.Contains("main")
to try to filter by this specific folder you mentioned.Yes, you could create a specific index which will only index items from a given folder. The simplest way would be to copy the
sitecore_web_index
definition and create your own changing theroot
node insidecrawler
.Like this:
Notice I only change the index name to *sitecore_MYFOLDER_index* and the root to /sitecore/MYFOLDER.
Then you create your content search using that new index definition