【问题标题】:C# Nest - ElasticSearchC# Nest - 弹性搜索
【发布时间】:2016-05-11 19:49:44
【问题描述】:

我是 ElasticSearch 的新手,我正在使用 NEST 运行我的查询。我需要能够在我的查询中添加 X 数量的过滤词。

目前我的查询如下所示:

var page = new Page
{
    Id = 1,
    Name = "JR-11 Hyper black"
};

var tags = new Dictionary<string, string[]>
{
    { "Size", new[] { "16", "17", "18" }},
    { "Color", new[] { "Bronze", "Hyper Black", "Flat Black" }}
};

page.Tags = tags;

ElasticClient.Index(page, idx => idx.Index("pages"));

var result = ElasticClient.Search<Page>(
    body => body.Query(query => query.ConstantScore(
        csq => csq.Filter(filter => filter.Term("tags.Size", "17" ))))
    .Take(1000));

var pages = result.Documents.ToList();

我遇到的问题是csq.Filter(filer =&gt; filter.Term("tags.Storlek")

我需要能够添加动态数量的此类过滤器。在我正在使用的 2.3 版本的文档中找不到任何内容。

【问题讨论】:

    标签: c# elasticsearch nest


    【解决方案1】:

    Fluent API 应该允许这样的事情:

    string[] filterTerms = { ... };
    
    var result = ElasticClient.Search<Page>(
        body => body.Query(query => query.ConstantScore(
        csq =>
        {
            var combinedFilters = csq.Filter(filter => filter.Term("tags.Size", "17" ));
    
            // add an additional, dynamic amount of filters
            foreach (string filterTerm in filterTerms)
                combinedFilters = combinedFilters.Filter(filter => filter.Term(filterTerm, ...));
    
            return combinedFilters;
        }))
        .Take(1000));
    

    【讨论】:

    • 谢谢!但是 filterTerms 应该包含什么?不应该以某种方式连接组合过滤器吗?而不是在循环中覆盖?
    • filterTerm 当然是由你定义的。您需要动态数量的过滤器,这就是您定义它们的地方。 combinedFilters 被覆盖,是的,但对象包含已定义的过滤器以及新添加的过滤器。通常实现实际上返回相同的对象。有关流畅界面的更多信息,请参阅en.wikipedia.org/wiki/Fluent_interface
    【解决方案2】:

    我最终得到了这个,似乎可以根据需要工作:)

     var result = ElasticClient.Search<Page>(
                body => body.Query(query => query.ConstantScore(csq => csq.Filter(f =>
                {
                    var ff = f.Term("tags.Size", "17");
    
                    // This will be replaced with a loop containing filter terms
                    ff &= f.Term("tags.Size", "16");
                    ff &= f.Term("tags.Size", "19");
    
                    return ff;
                }))).Take(1000));
    

    感谢您的回答让我找到了正确的方向,Thomas :)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多