路径
避免像这样查询路径:
context.GetQueryable<SearchResultItem>()
.Where(p => p.Path.StartsWith("/sitecore/content/Book"));
而是使用
context.GetQueryable<SearchResultItem>()
.Where(p => p.Paths.Contains(idOfBookFolderItem));
有关原因的更多信息,请参阅http://blog.paulgeorge.co.uk/2015/05/29/sitecore-contentsearch-api-filtering-search-on-folder-path/
方法
您需要一次性将整个查询交给搜索 API。
List<SearchResultItem> matches;
using (var context = ContentSearchManager.GetIndex(indexName).CreateSearchContext())
{
var predicate = PredicateBuilder.True<SearchResultItem>();
// must have this (.and)
predicate = predicate.And(p => p.Paths.Contains(bookFolderItem.ID));
// must have this (.and)
predicate = predicate.And(p => p.Name == searchTerm);
matches = context.GetQueryable<SearchResultItem>().Where(predicate).ToList();
}
这将返回 SearchResultItems 而不是 Items。如果您需要该项目,只需调用 GetItem。
Matches[i].GetItem()
空项目
这可能表明您的索引与数据库不同步。尝试从控制面板重新建立索引,或者在网络数据库的情况下,重新发布预期的内容。
搜索模板字段
这只是搜索项目名称。您只能在 SearchResultItem 类中指定通用字段。如果要搜索项目的特定字段,可以从 SearchResultItem 继承并添加这些字段。
public class BookSearchResultItem : SearchResultItem
{
[IndexField("Book Title")]
public string BookTitle { get; set; }
[IndexField("Book Author")]
public string BookAuthor { get; set; }
}
然后,您可以将其传递到查询中并在这些字段上进行搜索
List<BookSearchResultItem> matches;
using (var context = ContentSearchManager.GetIndex(indexName).CreateSearchContext())
{
var predicate = PredicateBuilder.True<BookSearchResultItem>();
// must have this (.and)
predicate = predicate.And(p => p.Paths.Contains(bookFolderItem.ID));
// must have this (.and)
predicate = predicate.And(
PredicateBuilder.False<BookSearchResultItem>() // in any of these fields
.Or(p => p.BookTitle == searchTerm)
.Or(p => p.BookAuthor == searchTerm)
.Or(p => p.Name == searchTerm));
matches = context.GetQueryable<BookSearchResultItem>().Where(predicate).ToList();
}
搜索所有“内容”
如果您发现必须指定显式字段是不必要的麻烦,或者您要在具有不同字段的不同模板中执行搜索,您可以改用特殊的计算“内容”字段,它将项目中的所有文本数据组合到一个索引字段中. 因此,而不是执行此操作的原始查询
predicate = predicate.And(p => p.Name == searchTerm);
你可以改为使用
predicate = predicate.And(p => p.Content == searchTerm);
它将在项目的任何字段中找到搜索词存在的结果。