- Published on
How to group and count results in Elasticsearch
- Authors
- Name
- Ridvan Chasan
- @RidvanChasan
How to group and count results in Elasticsearch
SQL query
SELECT Field, COUNT(Field)
FROM Table
GROUP BY Field
Query in Elasticsearch
GET /books/_search
{
"size": 0,
"aggs": {
"genre": {
"terms": {
"field": "genre"
}
}
}
}
Result
{
"error": {
"root cause" [
{
"type": "illegal _argument_exception",
"reason" : "Text fields are not optimised for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [title] in order to load field data by uninverting the inverted index. Note that this can use significant memory."
},
],
...
}
}
PUT /books
{
"mappings": {
"properties": {
"author": { "type": "text" },
"genre": { "type": "keyword" },
"title": { "type": "text" }
}
}
}