Elasticsearch:如何使用OR条件查询数组字段?

时间:2019-08-08 06:52:45

标签: elasticsearch

我有一些ElasticSearch文档,其中包含一个Array字段。

我希望能够搜索整个索引
要查找首先包含数组字段的文档,
然后,找到包含要搜索值的文档。

以下是我的数据-

{
  "took" : 633,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 4,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "demo",
        "_type" : "1",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "name" : "anon",
          "nick_name" : "an",
          "hobbies" : [
            "reading",
            "writing"
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "1",
        "_id" : "2",
        "_score" : 1.0,
        "_source" : {
          "name" : "anon2",
          "nick_name" : "an2",
          "hobbies" : [
            "playing",
            "studying"
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "1",
        "_id" : "3",
        "_score" : 1.0,
        "_source" : {
          "name" : "anon3",
          "nick_name" : "an3",
          "hobbies" : [
            "playing",
            "writing"
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "1",
        "_id" : "4",
        "_score" : 1.0,
        "_source" : {
          "name" : "anon4",
          "nick_name" : "an4"
        }
      }
    ]
  }
}

我想获取那些兴趣爱好数组包含“正在播放”或“正在学习” 值的文档
即。文档2和3

以下是我的数据创建查询-

POST /demo/_doc/1
{
  "name":"anon",
  "nick_name":"an",
  "hobbies":["reading","writing"]
}

POST /demo/_doc/2
{
  "name":"anon2",
  "nick_name":"an2",
  "hobbies":["playing","studying"]
}

POST /demo/_doc/3
{
  "name":"anon3",
  "nick_name":"an3",
  "hobbies":["playing","writing"]
}

POST /demo/_doc/4
{
  "name":"anon4",
  "nick_name":"an4"
}

GET demo/_search
{
  "query": {
    "match_all": {}
  }
}

以下查询可以让我进行一次搜索,但如何实现“或”条件?

GET demo/_search
{
  "query": {
    "match": {
      "hobbies": "playing"
    }
  }
}

2 个答案:

答案 0 :(得分:2)

我目前无法对其进行测试,但是可能是这样的:

GET demo/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "terms": {
            "hobbies": [
              "playing",
              "studying"
            ]
          }
        }
      ]
    }
  }
}

如果您的hobbies字段的类型为keyword

编辑: 按照documentation中的示例,它甚至可以更容易:

GET demo/_search
{
    "query" : {
        "terms" : {
            "hobbies" : ["playing", "studying"]
        }
    }
}

答案 1 :(得分:0)

我能够使用以下es查询解决此问题-

GET demo/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "hobbies": "playing"
          }
        },
        {
          "match": {
            "hobbies": "studying"
          }
        }
      ]
    }
  }
}