PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 24, 2022

[FIXED] How to get the last Elasticsearch document for each unique value of a field?

 October 24, 2022     elasticsearch     No comments   

Issue

I have a data structure in Elasticsearch that looks like:

{
  "name": "abc",
  "date": "2022-10-08T21:30:40.000Z",
  "rank": 3
}

I want to get, for each unique name, the rank of the document (or the whole document) with the most recent date.

I currently have this:

"aggs": {
  "group-by-name": {
    "terms": {
      "field": "name"
    },
    "aggs": {
      "max-date": {
        "max": {
          "field": "date"
        }
      }
    }
  }
}

How can I get the rank (or the whole document) for each result, and if possible, in 1 request ?


Solution

You can use below options

  1. Collapse
"collapse": {
    "field": "name"         
  },
  "sort": [
    {
      "date": { 
        "order": "desc"
      }
    }
  ]
  1. Top hits aggregation
{
  "aggs": {
    "group-by-name": {
      "terms": {
        "field": "name",
        "size": 100
      },
      "aggs": {
        "top_doc": {
          "top_hits": {
            "sort": [
              {
                "date": {
                  "order": "desc"
                }
              }
            ],            
            "size": 1
          }
        }
      }
    }
  }
}


Answered By - jaspreet chahal
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing