Rails Elasticsearch Aggregation

Rails elasticsearch aggregation

I was also struggling with this, but now I found out how to get the aggregation results.

If you're using the elasticsearch-rails with elasticsearch-model gems, when you run an aggregation on a model, you can get the buckets like in this example:

 agg = Model.search( 
query: { match: { param: 'value' } },
aggs: {my_aggregation_name: { terms: { field: :my_field} }}
)

In your RoR code:

agg.response["aggregations"]["my_aggregation_name"]["buckets"]

From that, you'll get a result like this:

[{"key"=>"banana",
"doc_count"=>1963,
"score"=>478.30920868573355,
"bg_count"=>2152},
{"key"=>"potato",
"doc_count"=>1212,
"score"=>315.68857496078505,
"bg_count"=>1243}, ...]

Then you can do whatever you want! Hope that helps!

Elasticsearch get results count of other indices with same query

Solution: You can aggregate on field _index.

"group_by_index": {
"terms": {
"field": "_index",
"size": "30"
}
}

Elastic search - aggregation filter for product options

The prerequisite for such aggregation is to have options field as nested.

Sample index mapping:

PUT test
{
"mappings": {
"properties": {
"title": {
"type": "keyword"
},
"options": {
"type": "nested",
"properties": {
"title": {
"type": "keyword"
},
"value": {
"type": "keyword"
}
}
}
}
}
}

Sample docs:

PUT test/_doc/1
{
"title": "Roncato Eglo",
"options": [
{
"title": "Mount type",
"value": "E27"
},
{
"title": "Material",
"value": "wood"
}
]
}

PUT test/_doc/2
{
"title": "Eglo",
"options": [
{
"title": "Mount type",
"value": "E27"
},
{
"title": "Material",
"value": "metal"
}
]
}

Assumption: For a given document a title under option appears only once. For e.g. there can exists only one nested document under option having title as Material.

Query for aggregation:

GET test/_search
{
"size": 0,
"aggs": {
"OPTION": {
"nested": {
"path": "options"
},
"aggs": {
"TITLE": {
"terms": {
"field": "options.title",
"size": 10
},
"aggs": {
"VALUES": {
"terms": {
"field": "options.value",
"size": 10
}
}
}
}
}
}
}
}

Response:

{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"OPTION" : {
"doc_count" : 4,
"TITLE" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "Material",
"doc_count" : 2,
"VALUES" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "metal",
"doc_count" : 1
},
{
"key" : "wood",
"doc_count" : 1
}
]
}
},
{
"key" : "Mount type",
"doc_count" : 2,
"VALUES" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "E27",
"doc_count" : 2
}
]
}
}
]
}
}
}
}


Related Topics



Leave a reply



Submit