Elasticsearch-如何组合“ AND”和“ OR”查询以获取两者的结果?

时间:2019-01-09 00:14:05

标签: elasticsearch

我正在尝试使用一个查询来获取两个查询的结果。

当前,我必须为每个多字串查询请求运行两个查询,然后将结果以编程方式组合到我觉得不合适的代码中。

其中一个查询使用AND运算符,其中一个查询使用OR运算符。

这是第一个查询:

GET my_index/_search
{
  "query": {
    "bool": {
      "must_not": [
        {"exists": {"field": "deleted"}}
      ],
      "must": [
        {
          "multi_match": {
            "query": "refuse eating",
            "fields": [
              "title^3",
              "desc^2",
              "body"
            ],
            "type": "best_fields",
            "operator": "AND"
          }
        }
      ],
      "filter": [
        {"term": {"kind": "article"}},
        {"term": {"status": "published"}}
      ]
    }
  }
}

这是第二个查询:

GET my_index/_search
{
  "query": {
    "bool": {
      "must_not": [
        {"exists": {"field": "deleted"}}
      ],
      "must": [
        {
          "multi_match": {
            "query": "refuse eating",
            "fields": [
              "title^3",
              "desc^2",
              "body"
            ],
            "type": "best_fields",
            "operator": "OR"
          }
        }
      ],
      "filter": [
        {"term": {"kind": "article"}},
        {"term": {"status": "published"}}
      ]
    }
  }
}

想法是在 top 处获取第一个查询的结果(使用AND运算符的查询),然后获取第二个查询的结果(使用OR运算符)低于第一结果。

有什么方法可以通过单个查询而不是两个查询来实现这一目标?

1 个答案:

答案 0 :(得分:3)

您可能可以利用bool/should因子更高的boost进行AND匹配:

GET my_index/_search
{
  "query": {
    "bool": {
      "must_not": [
        {
          "exists": {
            "field": "deleted"
          }
        }
      ],
      "minimum_should_match": 1,
      "should": [
        {
          "multi_match": {
            "query": "refuse eating",
            "fields": [
              "title^3",
              "desc^2",
              "body"
            ],
            "type": "best_fields",
            "operator": "AND",
            "boost": 2,                   <--- boost AND by 2 (or more)
            "_name": "and-match"
          }
        },
        {
          "multi_match": {
            "query": "refuse eating",
            "fields": [
              "title^3",
              "desc^2",
              "body"
            ],
            "type": "best_fields",
            "operator": "OR",
            "_name": "or-match"
          }
        }
      ],
      "filter": [
        {
          "term": {
            "kind": "article"
          }
        },
        {
          "term": {
            "status": "published"
          }
        }
      ]
    }
  }
}