【问题标题】:Elasticsearch query fails to return results when querying a nested object查询嵌套对象时,Elasticsearch 查询无法返回结果
【发布时间】:2018-01-11 00:01:34
【问题描述】:

我有一个看起来像这样的对象:

{
  "id": 123,
  "language_id": 1,
  "label": "Pablo de la Pena",
  "office": {
    "count": 2,
    "data": [
      {
        "id": 1234,
        "is_office_lead": false,
        "office": {
          "id": 1,
          "address_line_1": "123 Main Street",
          "address_line_2": "London",
          "address_line_3": "",
          "address_line_4": "UK",
          "address_postcode": "E1 2BC",
          "city_id": 1
        }
      },
      {
        "id": 5678,
        "is_office_lead": false,
        "office": {
          "id": 2,
          "address_line_1": "77 High Road",
          "address_line_2": "Edinburgh",
          "address_line_3": "",
          "address_line_4": "UK",
          "address_postcode": "EH1 2DE",
          "city_id": 2
        }
      }
    ]
  },
  "primary_office": {
    "id": 1,
    "address_line_1": "123 Main Street",
    "address_line_2": "London",
    "address_line_3": "",
    "address_line_4": "UK",
    "address_postcode": "E1 2BC",
    "city_id": 1
  }
}

我的 Elasticsearch 映射如下所示:

"mappings": {
  "item": {
    "properties": {
      "office": {
        "properties": {
          "data": {
            "type": "nested",
          }
        }
      }
    }
  }
}

我的 Elasticsearch 查询如下所示:

GET consultant/item/_search
{
  "from": 0,
  "size": 24,
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "language_id": 1
          }
        },
        {
          "term": {
            "office.data.office.city_id": 1
          }
        }
      ]
    }
  }
}

但是,如果我删除第二个 term 并只保留 language_id 子句,这将返回零结果,那么它会按预期工作。

我确信这是由于我对嵌套对象如何展平的误解,但我没有想法 - 我已经尝试了查询和映射的各种排列。

非常感谢任何指导。我正在使用 Elasticsearch 6.1.1。

【问题讨论】:

  • 发布office字段的完整映射。
  • 要搜索嵌套对象的字段,您必须将查询包装在 nested query 中。
  • 感谢@ChinHuang,我阅读了这个,并结合MrSimple的答案找到并理解了解决方案!

标签: elasticsearch


【解决方案1】:

我不确定您是否需要整个记录,此解决方案会提供每条具有 language_id: 1 且具有 office.data.office.id: 1 值的记录。

GET consultant/item/_search
{
  "from": 0,
  "size": 100,
  "query": {
    "bool":{
      "must": [
        {
          "term": {
            "language_id": {
              "value": 1
            }
          }
        },
        {
          "nested": {
            "path": "office.data",
            "query": {
              "match": {
                      "office.data.office.city_id": 1
              }
            }
          }
        }
      ]
    }
  }
}

我在我的测试索引中放置了 3 条不同的记录以防误击,一条具有不同的 language_id,一条具有不同的 office id,并且只返回匹配的一条。
如果你只需要办公数据,那就有点不同了,但还是可以解决的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 2015-05-31
    相关资源
    最近更新 更多