NEST Conditional filter query with multiple terms

后端 未结 3 1733
北恋
北恋 2020-12-25 14:21

I would like to do a ElasticSearch query like this:

{
    \"query\" :
    {
        \"bool\" :
        {
            \"filter\" : [
                {
                


        
3条回答
  •  悲哀的现实
    2020-12-25 14:50

    You can create a list of filters before you make a query if you want to check conditional filters as shown below:

    var nameList = new[] {"a", "b"};
    var colorList = new[] {1, 2};
    
    var filters = new List, QueryContainer>>();
    if (nameList.Any())
    {
         filters.Add(fq=> fq.Terms(t => t.Field(f => f.Name).Terms(nameList)));
    }
    
    if (colorList.Any())
    {
        filters.Add(fq => fq.Terms(t => t.Field(f => f.Color).Terms(colorList)));
    }
    
    ISearchResponse searchResponse =
         elasticClient.Search(x => x.Query(q => q
         .Bool(bq => bq.Filter(filters))));
    

    If you don't need to check any condition before making filter query then you can have something like that:

    ISearchResponse searchResponse =
    elasticClient.Search(x => x.Query(q => q
    .Bool(bq => bq
    .Filter(
            fq => fq.Terms(t => t.Field(f => f.Name).Terms(nameList)),
            fq => fq.Terms(t => t.Field(f => f.Color).Terms(colorList))
            ))));
    

提交回复
热议问题