【问题标题】:Elasticsearch source filtering object arrayElasticsearch 源过滤对象数组
【发布时间】:2018-03-18 02:36:23
【问题描述】:

对于在 Elasticsearch 中索引的文档,例如:

{
  "a": [
    {
      "b": [1,2,3],
      "c": "abcd1"
    },
    {
      "b": [4,5,6,7],
      "c": "abcd2"
    }
  ]
}

我们能否应用源过滤以使查询仅返回来自a 中所有对象的b 节点?

我尝试过这样的事情:

{
  "_source": {
    "excludes": [
      "a[*].c"
    ]
  },
  "query": {
    "match_all": {}
  }
}

但是,它没有用。

【问题讨论】:

标签: elasticsearch


【解决方案1】:

由于"a" 是一个对象数组来完成你想要的,你需要将"a" 定义为Nested 数据类型。请在此处阅读“对象数组”注释https://www.elastic.co/guide/en/elasticsearch/reference/current/array.html

因此您必须在映射中将“a”属性定义为nested 类型。我正在按照您的示例执行后续步骤:

1.- 定义映射

curl -XPUT 'localhost:9200/my_index?pretty' -H 'Content-Type: application/json' -d'
{
  "mappings": {
    "_doc": {
      "properties": {
        "a": {
          "type": "nested" 
        }
      }
    }
  }
}
'

2.- 使用您的示例数据创建文档1

curl -XPUT 'localhost:9200/my_index/_doc/1?pretty' -H 'Content-Type: application/json' -d'
{
  "a" : [
    {
      "b" : [1,2,3],
      "c" : "abcd1"
    },
    {
      "b" : [4,5,6,7],
      "c" :  "abcd2"
    }
  ]
}
'

3.- 这就是您的查询方式,请注意nested.path,当您必须指定您真正想要开始查询的路径时,然后是正常查询

curl -XGET 'localhost:9200/my_index/_search?pretty' -H 'Content-Type: application/json' -d'
{
  "_source": "a.b",
  "query": {
    "nested": {
      "path": "a",
      "query": {
        "match_all": {}
      }
    }
  }
}
'

这是每个对象中只有 b 字段的结果:

"took" : 4,
"timed_out" : false,
"_shards" : {
  "total" : 5,
  "successful" : 5,
  "skipped" : 0,
  "failed" : 0
},
"hits" : {
  "total" : 1,
  "max_score" : 1.0,
  "hits" : [
    {
      "_index" : "my_index",
      "_type" : "_doc",
      "_id" : "1",
      "_score" : 1.0,
      "_source" : {
        "a" : [
          {
            "b" : [1, 2, 3]
          },
          {
            "b" : [4, 5, 6, 7]
          }
        ]
      }
    }
  ]
}

这里是嵌套日期类型的 ElasticSearch 参考https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html

【讨论】:

  • 如果a[...] 是来自聚合查询的响应(即术语 aggs 中的 avg aggs)并且我只想要 b(排除 c)那么如何进行源过滤?
猜你喜欢
  • 1970-01-01
  • 2020-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多