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
358 views
in Technique[技术] by (71.8m points)

elasticsearch - How to get at least 1 document of each values?

I would like to fetch at list 1 document for each "adminId" i put into the array.

This is not a user index so i have multiple documents for each user.

Here is what i tried but i get multiple documents with the same adminId and some are missing:

{
  size: 10,
  query: {
    bool: {
      must: [
        {
          terms: {
            adminId: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
          }
        }
      ]
    }
  }
}

How to tell ES "fetch a least 1 document for each value i am giving you"?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

How to get (any) one document per given bucket?

Use top hits aggregatn as OP suggested.

curl -H 'Content-Type: application/json' localhost:9200/myindex/_search?pretty  -d '
{
   "size": 0,
   "query": {
      "bool": {
         "must": {
            "terms": {
               "adminId": ["CA", "NY", "TX"]
            }
         }
      }
   },
   "aggs": {
      "aggregation_name_1": {
         "terms": {
            "size": 10000,
            "field": "adminId"
         },
         "aggs": {
            "aggregation_name_2": {
               "top_hits": {
                  "size": 1
               }
            }
         }
      }
   }
}
'

Note

  • "size": 10000 means we want data for 10000 buckets (distinct adminId values). Adjust this value if you have more buckets.

  • "size": 1 means for every bucket, return (any) one document.


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

...