Elasticsearch用于索引数组元素

时间:2018-10-23 13:54:56

标签: elasticsearch nest elasticsearch-2.0

嗨,我想使用弹性搜索查询从索引中搜索数组元素

{
  "name": "Karan",
  "address": [
                        {
                            "city": "newyork",
                            "zip": 12345
                        },
                        {
                            "city": "mumbai",
                            "zip": 23456
                        }]
}}

当我尝试使用匹配查询进行搜索时,它不起作用

{
    "query": {
      "bool": {
        "must": [
          {
            "match": {
              "address.city": "newyork"
            }
          }
        ]
      }
    }
  }

当我访问简单的字段(如“ name”:“ Karan”)时,它仅适用于数组元素。

2 个答案:

答案 0 :(得分:0)

由于嵌套对象被索引为单独的隐藏文档,因此我们无法直接对其进行查询。相反,我们必须使用 嵌套查询 来访问它们:

GET /my_index/blogpost/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "title": "eggs" 
          }
        },
        {
          "nested": {
            "path": "comments", 
            "query": {
              "bool": {
                "must": [ 
                  {
                    "match": {
                      "comments.name": "john"
                    }
                  },
                  {
                    "match": {
                      "comments.age": 28
                    }
                  }
                ]
              }
            }
          }
        }
      ]
}}}

See the docs

答案 1 :(得分:0)

我遵循的方式。

映射:

{
  "mappings": {
    "job": {
      "properties": {
        "name": {
          "type": "text"
        },
        "skills": {
          "type": "nested",
          "properties": {
            "value": {
              "type": "text"
            }
          }
        }
      }
    }
  }

记录

[{"_index":"jobs","_type":"job","_id":"2","_score":1.0,"_source":{"name":"sr soft eng","skills":[{"value": "java"}, {"value": "oracle"}]}},{"_index":"jobs","_type":"job","_id":"1","_score":1.0,"_source":{"name":"sr soft eng","skills":[{"value": "java"}, {"value": "oracle"}, {"value": "javascript"}]}},

搜索查询

{
  "query": {
    "nested": {
      "path": "skills",
      "query": {
        "bool": {
          "must": [
            { "match": {"skills.value": "java"}}
          ]
        }
      }
    }
  }
}