如何使用Lucene索引Sitecore中的子内容?

时间:2014-12-05 15:04:13

标签: asp.net-mvc lucene sitecore

我正在使用Sitecore 7.2和MVC以及构建页面的组件方法。这意味着页面基本上是空的,内容来自页面上放置的各种渲染。但是,我希望搜索结果返回主页,而不是单个内容。

这是我到目前为止的基本代码:

public IEnumerable<Item> GetItemsByKeywords(string[] keywords)
{
    var index = ContentSearchManager.GetIndex("sitecore_master_index");
    var allowedTemplates = new List<ID>();
    IEnumerable<Item> items;

    // Only Page templates should be returned
    allowedTemplates.Add(new Sitecore.Data.ID("{842FAE42-802A-41F5-96DA-82FD038A9EB0}"));

    using (var context = index.CreateSearchContext(SearchSecurityOptions.EnableSecurityCheck))
    {
        var keywordsPredicate = PredicateBuilder.True<SearchResultItem>();
        var templatePredicate = PredicateBuilder.True<SearchResultItem>();
        SearchResults<SearchResultItem> results;

        // Only return results from allowed templates
        templatePredicate = allowedTemplates.Aggregate(templatePredicate, (current, t) => current.Or(p => p.TemplateId == t));

        // Add keywords to predicate
        foreach (string keyword in keywords)
        {
            keywordsPredicate = keywordsPredicate.And(p => p.Content.Contains(keyword));
        }

        results = context.GetQueryable<SearchResultItem>().Where(keywordsPredicate).Filter(templatePredicate).GetResults();
        items = results.Hits.Select(hit => hit.Document.GetItem());
    }

    return items;
}

2 个答案:

答案 0 :(得分:1)

您可以在索引中创建一个计算字段,该字段查看页面上的渲染并解析每个渲染​​的数据源项。获得这些项目之后,您可以将其字段编入索引并将所有这些数据连接在一起。

一种选择是使用本地&#34;内容&#34;计算字段本身就是全文搜索使用的。

答案 1 :(得分:0)

另一种解决方案是将HttpRequest恢复到您发布的网站,并基本上抓取HTML。这可确保所有渲染都包含在索引中。

您可能不希望索引常用部分,例如“菜单”和“页脚”,因此请使用HTMLAgilityPackFizzlerEx仅返回特定父容器的内容。你需要更聪明地去除内部容器。请记住也要删除html标签:)

using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;

//get the page
var web = new HtmlWeb();
var document = web.Load("http://localsite/url-to-page");
var page = document.DocumentNode;

var content = page.QuerySelector("div.main-content");