Query to find if a field exists in last 7 hours

I am trying to find documents containing opsgenieAction:create in the last 7 hours. I constructed the following query but somehow the result is not as expected.

can someone help to find what is wrong here?

Query :

GET my-index*/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "date": {
              "gte": "now-7h",
              "lt" : "now"
            }
          }
        }
      ],
      "should": [
        {
          "query_string": { "fields": [
              "opsgenieAction"
            ],
              "query": "opsgenieAction:create"
          }
        }
      ]
    }
  }
}

Response :

response: 
{
  "took" : 658,
  "timed_out" : false,
  "_shards" : {
    "total" : 276,
    "successful" : 276,
    "skipped" : 275,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 0,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  }
}

You made the opsgenieAction:create clause optional by putting it in the should section.
Place it in the filters section along with the other mandatory clause.

@Mark_Harwood thanks for replying.

do you mean like this ?

GET my-index*/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "date": {
              "gte": "now-7h",
              "lt": "now"
            }
          },
          "term": {
            "opsgenieAction": "create"
          }
        }
      ]
    }
  }
}

Close. The filter array should have 2 objects [ {...}, {...}] not one.

I tried the way you suggested, the query was executed successfully but again result is not as expected.

Query :

GET my-index*/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "date": {
              "gte": "now-7h",
              "lt": "now"
            }
          }
        },
       {
         "term": {
           "opsgenieAction": "create"
         }
       }
      ]
    }
  }
}

Response :

{
  "took" : 250,
  "timed_out" : false,
  "_shards" : {
    "total" : 276,
    "successful" : 276,
    "skipped" : 275,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 0,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  }
}

To help further I'd need the following JSON:

  1. Your index mapping
  2. An example doc which you expect to match but doesn't

sure @Mark_Harwood....Both are as following. I have removed some information, but field names are as it is.

Sample doc:

mapping of my index :

Your example document has no field at the root called date. Your query is expecting that

1 Like

@Mark_Harwood got it !!

yeah it works now. Thanks alot :pray:

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.