在elasticsearch中使用MinimumShouldMatch和术语查询

时间:2015-03-30 13:53:00

标签: elasticsearch nest elasticsearch-net

我在nest中为弹性搜索编写了一个与国家/地区列表匹配的查询 - 只要列表中的任何国家/地区出现在ESCountryDescription(国家/地区列表)中,它就会进行匹配。我只想匹配CountryList中的所有国家/地区匹配ESCountryDescription。我相信我需要使用MinimumShouldMatch,例如本例http://www.elastic.co/guide/en/elasticsearch/reference/0.90/query-dsl-terms-query.html

a.Terms(t => t.ESCountryDescription, CountryList)

但是我找不到将MinimumShouldMatch添加到上面的查询中的方法。

2 个答案:

答案 0 :(得分:2)

您可以在MinimumShouldMatch中应用TermsDescriptor patameter。这是一个例子:

var lookingFor = new List<string> { "netherlands", "poland" };

var searchResponse = client.Search<IndexElement>(s => s
    .Query(q => q
        .TermsDescriptor(t => t.OnField(f => f.Countries).MinimumShouldMatch("100%").Terms(lookingFor))));

var lookingFor = new List<string> { "netherlands", "poland" };

var searchResponse = client.Search<IndexElement>(s => s
                .Query(q => q
                    .TermsDescriptor(t => t.OnField(f => f.Countries).MinimumShouldMatch(lookingFor.Count).Terms(lookingFor))));

这就是整个例子

class Program
{
    public class IndexElement
    {
        public int Id { get; set; }
        [ElasticProperty(Index = FieldIndexOption.NotAnalyzed)]
        public List<string> Countries { get; set; }
    }

    static void Main(string[] args)
    {
        var indexName = "sampleindex";

        var uri = new Uri("http://localhost:9200");
        var settings = new ConnectionSettings(uri).SetDefaultIndex(indexName).EnableTrace(true);
        var client = new ElasticClient(settings);

        client.DeleteIndex(indexName);

        client.CreateIndex(
            descriptor =>
                descriptor.Index(indexName)
                    .AddMapping<IndexElement>(
                        m => m.MapFromAttributes()));

        client.Index(new IndexElement {Id = 1, Countries = new List<string> {"poland", "germany", "france"}});
        client.Index(new IndexElement {Id = 2, Countries = new List<string> {"poland", "france"}});
        client.Index(new IndexElement {Id = 3, Countries = new List<string> {"netherlands"}});

        client.Refresh();

        var lookingFor = new List<string> { "germany" };

        var searchResponse = client.Search<IndexElement>(s => s
            .Query(q => q
                .TermsDescriptor(t => t.OnField(f => f.Countries).MinimumShouldMatch("100%").Terms(lookingFor))));
    }
}

关于你的问题

  1. 条款:&#34;荷兰&#34;你将获得Id 3
  2. 的文件
  3. 条款:&#34;波兰&#34;和&#34;法国&#34;您将获得Id 1和2
  4. 的文件
  5. 条款:&#34;德国&#34;你将获得Id 1
  6. 的文件
  7. 条款:&#34;波兰&#34;,&#34;法国&#34;和&#34;德国&#34;你会得到文件 与Id 1
  8. 我希望这是你的观点。

答案 1 :(得分:1)

而不是做

.Query(q => q
    .Terms(t => t.ESCountryDescription, CountryList))

您可以使用以下命令

.Query(q => q
    .TermsDescriptor(td => td
        .OnField(t => t.ESCountryDescription)
        .MinimumShouldMatch(x)
        .Terms(CountryList)))

有关elasticsearch-net Github存储库中的单元测试,请参阅this

相关问题