Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

search - Elasticsearch: Aggregation on filtered nested objects to find unique values

I have an array of objects (tags) in each document in Elasticsearch 5:

{
    "tags": [
        { "key": "tag1", "value": "val1" },
        { "key": "tag2", "value": "val2" },
        ...
    ]
}

Now I want to find unique tag values for a certain tag key. Something similiar to this SQL query:

SELECT DISTINCT(tags.value) FROM tags WHERE tags.key='some-key'

I have came to this DSL so far:

{
    "size": 0,
    "aggs": {
        "my_tags": {
            "nested": {
                "path": "tags"
            },
            "aggs": {
                "filter" : { "terms": { "tags.key": "tag1" } },
                "aggs": {
                    "my_tags_values": {
                        "terms" : {
                            "field" : "tags.value",
                            "size": 9999
                         }
                    }                   
                }
            }
        }
    }
}

But It is showing me this error:

[terms] unknown field [tags.key], parser not found.

Is this the right approach to solve the problem? Thanks for your help.

Note: I have declared the tags field as a nested field in my mapping.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You mixed up things there. You wanted probably to add a filter aggregation, but you didn't give it any name:

{
  "size": 0,
  "aggs": {
    "my_tags": {
      "nested": {
        "path": "tags"
      },
      "aggs": {
        "my_filter": {
          "filter": {
            "terms": {
              "tags.key": [
                "tag1"
              ]
            }
          },
          "aggs": {
            "my_tags_values": {
              "terms": {
                "field": "tags.value",
                "size": 9999
              }
            }
          }
        }
      }
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...