在 Elasticsearch 中构建多个过滤器

Build multiple filter in Elasticsearch

您能否建议我如何基于多个过滤器构建查询。 目前,我想使用以下过滤器实现搜索功能:

要求是,当county或city没有选择值时,查询假设你是搜索所有的国家和城市。 如果有选择的县市,则以选择的县市为准。

我从下面的查询开始。

static void Main(string[] args)
{   
    var uri = new Uri("http://localhost:9200");
    var connectionPool = new SingleNodeConnectionPool(uri);
    var settings = new ConnectionSettings(connectionPool);

    var client = new ElasticClient(settings);

    if (counties.Count > 0) 
    {
        foreach(string country in counties)
        {
            // Add a query to be added in client.Search     
        }
    }

    if (cities.Count > 0)
    {
        foreach(string city in cities)
        {
            // Add a query to be added in client.Search
        }
    }

    client.Search<Product>(s => s
                            .Query(q => q
                                .Bool(b => b
                                    .Must(mu => mu
                                        .Match(m => m
                                            .Field(f => f.ProductName)
                                            .Query("some text")
                                        ),
                                        .
                                    )
                                )
                            )
                        );
}

您可以使用 terms query:

{
  "query": {
    "bool": {
      "must": [
        { "match": { "field": "productName", "query": "some text"}},
        // Only add this filter if the array is not empty
        { "terms": { "Country": ["Canada", "France"]}},
        // Same here
        { "terms": { "City": ["Ottawa", "Paris"]}},
      ]
    }
  }
}

我只是回答我自己的问题。目前,我采用了这种方法。

var sd = new SearchDescriptor<object>();
var qc = new QueryContainer();
var qd = new QueryContainerDescriptor<object>();

sd.From(0);
sd.Size(100);
sd.Index("Products");
sd.Type("Product");

if (!string.IsNullOrEmpty(title))
{
    qc = qd.Match(m1 => m1
        .Field("title")
        .Query(title)
    );
}

if (countries.Count > 0)
{
    qc = qd.Terms(t => t
            .Field("country")
            .Terms(countries.ToArray())
        );
}

if (cities.Count > 0)
{
    qc = qd.Terms(t => t
            .Field("city")
            .Terms(cities.ToArray())
        );
}

sd.Query(q => q
        .Bool(b => b
            .Must(qc)
        )
    );

var result = client.Search<object>(s => s = sd);