Home > Enterprise >  Elasticsearch Last document of multiple term queries
Elasticsearch Last document of multiple term queries

Time:11-17

I need to get the last document of each interface, I have played around with different queries but I can get the desired result, below is my las attempt.

Can you help me to get the last document of each interface where the field throughput exist?

Thanks

GET /interface-2021.11/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "interface_name.keyword": {
              "value": "Gi0/0/2 on (EXT-01)"
            }
          }
        },
        {
          "term": {
            "interface_name.keyword": {
              "value": "Gi0/0/1 on (EXT-02)"
            }
          }
        },
        {
          "term": {
            "interface_name.keyword": {
              "value": "Ethernet1/61 on (DC-01)"
            }
          }
        },
        {
          "term": {
            "interface_name.keyword": {
              "value": "Ethernet1/17 on (DC-02)"
            }
          }
        }
      ],
      "minimum_should_match": 1,
      "filter": [
        {
          "exists": {
            "field": "throughput"
          }
        }
      ]
    }
  },
  "aggs": {
    "top_date": {
      "top_hits": {
        "sort": [
          {
            "@timestamp": {
              "order": "desc"
            }
          }
        ]
      }
    }
  }
}

CodePudding user response:

Good job, you're on the right path! You just need to aggregate by interface_name.keyword and get the top hit for each interface.

Here is the query that will work as you expect:

{
  "size": 0,
  "query": {
    "bool": {
      "filter": [
        {
          "terms": {
            "interface_name.keyword": [
              "Gi0/0/2 on (EXT-01)",
              "Gi0/0/1 on (EXT-02)",
              "Ethernet1/61 on (DC-01)",
              "Ethernet1/17 on (DC-02)"
            ]
          }
        },
        {
          "exists": {
            "field": "throughput"
          }
        }
      ]
    }
  },
  "aggs": {
    "interfaces": {
      "terms": {
        "field": "interface_name.keyword"
      },
      "aggs": {
        "top_date": {
          "top_hits": {
            "sort": [
              {
                "@timestamp": {
                  "order": "desc"
                }
              }
            ]
          }
        }
      }
    }
  }
}
  • Related