【问题标题】:select matching objects from array in elasticsearch从elasticsearch中的数组中选择匹配的对象
【发布时间】:2015-07-30 18:15:08
【问题描述】:
{
    class: 1,
    users: [{
        name: 'abc',
        surname: 'def'
    }, {
        name: 'xyz',
        surname: 'wef'
    }, {
        name: 'abc',
        surname: 'pqr'
    }]
}

我有一个类似上述对象的文档结构,我只想返回名称为“abc”的用户,但问题是它与名称“abc”匹配但返回 所有数组。我只想要匹配的用户。

映射 -

{
        "class":"string",
        "users" : {
            "type" : "nested",
            "properties": {
                "name" : {"type": "string" },
                "surname"  : {"type": "string" }
            }
        }
    }

【问题讨论】:

  • 你能显示你的查询吗?可能还有你的映射?

标签: elasticsearch


【解决方案1】:

那么,如果您将 users 字段映射为 nested 类型,这是一个好的开始!

使用nested inner_hits,您可以通过如下查询仅检索匹配的用户名:

{
  "_source": false,
  "query": {
    "nested": {
      "path": "users",
      "inner_hits": {        <---- this is where the magic happens
        "_source": [
          "name"
        ]
      },
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "users.name": "abc"
              }
            }
          ]
        }
      }
    }
  }
}

【讨论】:

  • 我们可以做 "_source": false for specific _type 吗?
  • 如果您的意思是这样,您绝对可以通过直接在 URL /my_index/my_type/_search 中指定类型来将搜索查询缩小到指定类型。
  • 我们能得到所有只有匹配嵌套字段的普通字段吗?像{类:1,用户:[{名称:'abc',姓氏:'def'}]}
  • @JayShah 如果你设置了_source: true,它应该会得到你想要的
  • 是的,但是如果我设置 _source: true,它会给我所有嵌套的对象。我只需要匹配嵌套对象。比如 { class: 1, users: [{ name: 'abc', surname: 'def' }] } 这可能吗?
猜你喜欢
  • 2015-10-30
  • 2019-02-28
  • 1970-01-01
  • 2018-09-24
  • 2018-10-17
  • 2018-08-29
  • 2015-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多