How do I create an “OR” filter using elasticsearch-dsl-py?

强颜欢笑 提交于 2019-12-03 12:58:58

Solution:

s = Search(using=client,
           index="my_index"
    ).filter(
        "term", status=PUBLISHED
    ).filter(
        "or", [F("range", start_publication={"lte": now}, ),
               F("missing", field="start_publication")]
    ).filter(
        "or", [F("range", end_publication={"gte": now}, ),
               F("missing", field="end_publication")]
    )

Which turns into:

{  
   "query":{  
      "filtered":{  
         "filter":{  
            "bool":{  
               "must":[  
                  {  
                     "term":{  
                        "status":"published"
                     }
                  },
                  {  
                     "or":{  
                        "filters":[  
                           {  
                              "range":{  
                                 "start_publication":{  
                                    "lte":"2015-02-17T03:45:00.245012+00:00"
                                 }
                              }
                           },
                           {  
                              "missing":{  
                                 "field":"start_publication"
                              }
                           }
                        ]
                     }
                  },
                  {  
                     "or":{  
                        "filters":[  
                           {  
                              "range":{  
                                 "end_publication":{  
                                    "gte":"2015-02-17T03:45:00.245012+00:00"
                                 }
                              }
                           },
                           {  
                              "missing":{  
                                 "field":"end_publication"
                              }
                           }
                        ]
                     }
                  }
               ]
            }
         },
         "query":{  
            "match_all":{  

            }
         }
      }
   }
}

Hopefully this can be included in the elasticsearch-dsl-py documentation in the future.

Michael

With Elasticsearch 2.x (and elasticsearch-dsl > 2.x) you can't apply filters as in @theslow1's comment anymore. Instead you have to construct your filter by combining Qs:

search = Search(using=esclient, index="myIndex")
firstFilter = Q("match", color='blue') & Q("match", status='published')
secondFilter = Q("match", color='yellow') & Q("match", author='John Doe')
combinedFilter = firstFilter | secondFilter
search = search.query('bool', filter=[combinedFilter])

The search.query('bool', filter=[combinedQ]) applies the Q-criteria as filter as described in the elasticsearch-dsl documentation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!