Elasticsearch:如果字段存在于多索引查询中,则有条件地过滤查询

时间:2016-09-05 13:22:07

标签: elasticsearch

我有一个跨多个索引的一般搜索查询。一些索引有一个名为is_published的字段,有些字段有date_review字段,有些字段都有。{/ p>

我正在努力编写一个查询来搜索字段并过滤上面提到的字段,但仅限于它们存在。我已经设法使用missing和/或exists在各个字段上实现了我想要的效果,但它排除了其他变体。

在英语中,我想将文档保存在以下结果中:

  1. is_published为真或该字段不存在
  2. date_review将来或该字段不存在
  3. 因此,如果某个文档有is_published并且该文档为false,请将其删除。如果文档过去有date_review,请将其删除。如果将来有is_published == falsedate_review,请将其删除。

    我希望这有道理吗?

    为了回答,假设文件可能如下所示:

    //  Has `is_published` flag
    {
        "label": "My document",
        "body": "Lorem ipsum doler et sum.",
        "is_published": true
    }
    
    //  Has `date_review` flag
    {
        "label": "My document",
        "body": "Lorem ipsum doler et sum.",
        "date_review": "2017-01-01"
    }
    
    
    //  Has both `is_published` and `date_review` flags
    {
        "label": "My document",
        "body": "Lorem ipsum doler et sum.",
        "is_published": true
        "date_review": "2017-01-01"
    }
    

    目前,我的[未经过滤]查询如下所示:

    {
      "index": "index-1,index-2,index-3",
      "type": "item",
      "body": {
        "query": {
          "filtered": {
            "query": {
              "multi_match": {
                "query": "my serach phrase",
                "type": "phrase_prefix",
                "fuzziness": null,
                "fields": [
                  "label^3",
                  "body",
                ]
              }
            },
            "filter": []
          }
        }
      }
    }
    

    非常感谢任何指示。

    感谢。

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的查询:

{
  "query": {
    "filtered": {
      "query": {
        "multi_match": {
          "query": "my serach phrase",
          "type": "phrase_prefix",
          "fuzziness": null,
          "fields": [
            "label^3",
            "body"
          ]
        }
      },
      "filter": {
        "bool": {
          "must": [
            {
              "bool": {
                "minimum_should_match": 1,
                "should": [
                  {
                    "missing": {
                      "field": "is_published"
                    }
                  },
                  {
                    "term": {
                      "is_published": true
                    }
                  }
                ]
              }
            },
            {
              "bool": {
                "minimum_should_match": 1,
                "should": [
                  {
                    "missing": {
                      "field": "date_review"
                    }
                  },
                  {
                    "range": {
                      "date_review": {
                        "gt": "now"
                      }
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }
  }
}
相关问题