代码之家  ›  专栏  ›  技术社区  ›  ab 16

Elasticsearch 5.4-如果项存在,则按项过滤,如果项不存在,则不过滤

  •  0
  • ab 16  · 技术社区  · 7 年前

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

    如果my_字段上的过滤器不影响查询分数,只进行过滤,那就太好了。

    这是我得到的最接近的结果。如果你能帮我的话,我会自责一个小时。

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

    body = {
        'query': {
            'bool': {
                'must': {
                    'multi_match': {
                        'query': 'pangolin',
                        'fields': ['_all', '_partials']
                    }
                },
                "should": {
                    "must_not": {
                        "exists": {
                            "field": "my_field"
                        }
                    }
                },
                "should": {
                    'term': {
                        'my_field': True
                    }
                }
            }
        }
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   ab 16    7 年前

    以下似乎是我需要的。 文档必须与“穿山甲”匹配,并且文档在两个应选项上过滤。只有一个should需要匹配。

    https://www.elastic.co/guide/en/elasticsearch/reference/5.4/query-dsl-bool-query.html (请参见关键词:过滤器和应)。

    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"
                                        }
                                    }
                                }
                            }
                        ]
                    }
                }
            }
        }
    }
    
        2
  •  1
  •   ab 16    7 年前

    你试过这样的东西吗?

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