I am trying to implement autocomplete feature using elasticsearch. The structure of the index which I am working on is this
"title": "blog post 1",
"body": "body of the blog post",
"category": "programming",
"locations": [
{"name": "united states"},
{"name": "new york"},
{"name": "venice"}
]
I am trying to use nested aggregations. The mapping which I am using is this
{
blog : {
mappings : {
tag : {
properties : {
body : {
type : string
},
category : {
type : string
},
locations : {
properties : {
name : {
type : string
}
}
},
title : {
type : string
}
}
}
}
}
}
The query which is supposed to aggregate the results on the basis of locations.name
is
GET /blog/tag/_search
{
"size": 0,
"query": {
"match": {
"locations.name": "montreal"
}
},
"aggs": {
"aggregated_locations": {
"nested": {
"path": "locations"
},
"aggs": {
"filtered_locations": {
"terms": {
"fields": "locations.name"
}
}
}
}
}
}
Currently I am executing the above request using the chrome plugin for elasticsearch. The above query gives out an error, which is very long but I can post it too if someone prompts. I guess I might be wrong in interpreting the meaning of nested aggregations, which means my mapping is wrong. But I am not able to figure out where the problem is.
There are some missing parts in your mapping, you need to set the locations field to nested
type and not analyzing the inner field to be able to aggregate with regards of your expectations:
PUT blog
{
"mappings": {
"tag": {
"properties": {
"body": {
"type": "string"
},
"category": {
"type": "string"
},
"locations": {
"type": "nested",
"properties": {
"name": {
"type": "string",
"index": "not_analyzed"
}
}
},
"title": {
"type": "string"
}
}
}
}
}
Then run following query to filter on nested field, and aggregate on nested field as well:
GET blog/_search
{
"size": 0,
"query": {
"nested": {
"path": "locations",
"query": {
"match": {
"locations.name": "montreal"
}
}
}
},
"aggs": {
"aggregated_locations": {
"nested": {
"path": "locations"
},
"aggs": {
"filtered": {
"terms": {
"field": "locations.name"
}
}
}
}
}
}
Those query can be copied / pasted in sense (https://www.elastic.co/guide/en/sense/current/installing.html)