Elasticsearch 5.4 - 如果术语存在则按术语过滤,当术语不存在时不过滤

Elasticsearch 5.4 - filter by term if the term exists and don't filter when term is not present

我正在搜索多种类型。返回的类型之一有一个名为 my_field 的字段。返回的其他类型没有该字段。我想要该术语不存在的所有结果,并且仅当该术语存在时该字段具有值 True 的结果。

如果 my_field 上的过滤器对查询分数没有贡献并且仅被过滤,那就太好了。

这是我得到的最接近的。如果你帮我,我会自虐1小时

(不要用这个是错误的!)

body = {
    'query': {
        'bool': {
            'must': {
                'multi_match': {
                    'query': 'pangolin',
                    'fields': ['_all', '_partials']
                }
            },
            "should": {
                "must_not": {
                    "exists": {
                        "field": "my_field"
                    }
                }
            },
            "should": {
                'term': {
                    'my_field': True
                }
            }
        }
    }
}

你试过这样的东西吗?

$ curl -XPOST localhost:9200/type1,type2/_search -d '{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "my_field": true
          }
        },
        {
          "constant_score": {
            "filter": {
              "not_missing": {
                "field": "type2.my_field"
              }
            }
          }
        }
      ]
    }
  }
}'

让我知道这是否可行。祝你好运!

以下好像是我需要的。 文档必须在 'pangolin' 上匹配,并且文档在 2 个应该上被过滤。只有 1 个应该匹配。

https://www.elastic.co/guide/en/elasticsearch/reference/5.4/query-dsl-bool-query.html(见关键词:filter 和 should)。

body = {
    "query": {
        'bool': {
            'must': {
                'multi_match': {
                    'query': 'pangolin',
                    'fields': ['_all', '_partials']
                }
            },
            "filter": {
                "bool": {
                    "should": [{
                            "term": {
                                "my_field": True
                            }
                        },
                        {
                            "bool": {
                                "must_not": {
                                    "exists": {
                                        "field": "my_field"
                                    }
                                }
                            }
                        }
                    ]
                }
            }
        }
    }
}