Nerve
Nerve

Reputation: 6881

Group results returned by elasticsearch query based on query terms

I am very new with elasticsearch. I am facing an issue building a query. My document structure is like:

{
  latlng: {
    lat: '<some-latitude>',
    lon: '<some-longitude>'
  },
  gmap_result: {<Some object>}
}

I am doing a search on a list of lat-long. For each coordinate, I am fetching a result that is within 100m. I have been able to do this part. But, the tricky part is that I do not know which results in the output correspond to the which query term. I think this requires using aggregations at some level, but I am currently clueless on how to proceed on this.

Upvotes: 1

Views: 657

Answers (1)

EricPSU
EricPSU

Reputation: 163

An aggregate query is the correct approach. You can learn about them here:

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html

An example is below. In this example, I am using a match query to find all instances of the word test in the field title and then aggregating the field status to count the number of results with the word test that are in each status.

GET /my_index/_search
{
  "query": {
    "bool": {
      "must": [
       {
          "match": {
            "title": "*test*"
          }
        }
      ]
    }
  },
  "aggs": {
    "count_by_status": {
      "terms": {
        "field": "status"
      }
    }
  },
  "size": 0
}

The results look like this:

{
  "took": 3,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 346,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "count_by_status": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "Open",
          "doc_count": 283
        },
        {
          "key": "Completed",
          "doc_count": 36
        },
        {
          "key": "On Hold",
          "doc_count": 12
        },
        {
          "key": "Withdrawn",
          "doc_count": 10
        },
        {
          "key": "Declined",
          "doc_count": 5
        }
      ]
    }
  }
}

If you provide your query, it would help us give a more specific aggregate query for you to use.

Upvotes: 1

Related Questions