简体   繁体   中英

How to aggregate a 'non - keyword' field in elasticsearch?

I am trying to write an elastic-search query that should list all distinct values held by various fields in a document.When the fields are of type Keyword,the term aggregate query works fine and I can see the values with their counts listed in the buckets.But, I don't get any result when I query for the distinct citrus fruit types, the mapping is as shown below:

{   
    "vegetables":{
      "type": "text",
      "fields": {
         "keyword" : {
            "type" : "keyword",
            "ignore_above": 256
          }
        }
     }, 
    "fruits": {
        "properties": {
            "citrus": {
                "properties": {
                    "orange": {
                        "type": "long"
                    },
                    "lemon": {
                        "type": "long"
                    },
                    "kiwi": {
                        "type": "long"
                    }
                }
            }
        }
    }
}

and the result I am expecting is :

"aggregations": {
  "distinct_citrusy_fruits"{
     "buckets" : [
       {
         "key":"oranges",
         "doc_count": 23
       },
       {
         "key":"lemon",
         "doc_count": 21
       },
       {
         "key":"kiwi",
         "doc_count": 23
       }
      ]
   }
}

when I make a term aggregation for the "vegetables" field (which is a keyword type) i am able to get the buckets as above. How to get the distinct counts in this case?Also, I don't have the option to change the document format.

EDIT- the only workaround I have found till now is to call the mappings api and then parse the nested JSON in my code to get the key values,if there is any better solution possible, please add an answer here.

I think you cannot query or run aggregations on the field names, only on values. For the fruits i expect the following mapping:

{
    "fruits": {
        "properties": {
            "citrus": {
                "properties": {
                    "kind": {
                        "type": "keyword"
                    },
                    "count": {
                        "type": "long"
                    }
                }
            }
        }
    }
}

Maybe you can use the _field_names field which contains every fieldname that has a value. ( https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-field-names-field.html )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM