Help me rewrite my elasticsearch query


(Yodog) #1

I need some help rewriting my elasticsearch query.

What i need is:

1- to show a single record if there is an exact match on the two fields verb and sessionid.raw (partial matches are not accepted).

"must": [
    { "match" : { "verb" : "login" } },
    { "term"  : { "sessionid.raw" : strSessionID } },
]

OR

2- to show the top 5 records (sorted by _score DESC and @timestamp ASC) that match some other fields, giving a boost if the records are between the specified time range.

"must": [
    { "match" : { "verb" : "login" } },
    { "term"  : { "pid" : strPID } },
],
"should": [
    { "match" : { "user.raw" : strUser } },
    { "range" : { "@timestamp" : {
        "from"      : QueryFrom,
        "to"        : QueryTo,
        "format"    : DateFormatElastic,
        "time_zone" : "America/Sao_Paulo",
        "boost"     : 2 }
    } },
]

The code below is almost doing what i want.
Right now it boosts sessionid.raw to the top if found, but the remaining records are not being discarded.

var objQueryy = {
    "fields" : [ "@timestamp", "program", "pid", "sessionid.raw", "user", "frontendip", "frontendname", "_score" ],
    "size"   : ItemsPerPage,
    "sort"   : [ { "_score" : { "order": "desc" } }, { "@timestamp" : { "order" : "asc" } } ],
    "query"  : {
        "bool": {
            "must": [
                { "match" : { "verb" : "login" } },
                { "term"  : { "pid" : strPID } },
                { "bool":  {
                    "should": [
                        { "match" : { "user.raw" : strUser } },
                        { "match" : { "sessionid.raw": { "query": strSessionID, "boost" : 3 } } },
                        { "range" : { "@timestamp" : { "from": QueryFrom, "to": QueryTo, "format": DateFormatElastic, "time_zone": "America/Sao_Paulo" } } },
                    ],
                }},
            ],
        },
    },
}

(Adrien Grand) #2

The easiest way to do this would be to run 2 search requests: a first one for the exact match, and then the other one if the first one did not yield any results.


(Yodog) #3

Thanks.

And about the hard way...

Is it possible to do it with only one query, and im just missing the logic behind it?

Or its not possible at all?


(Adrien Grand) #4

It is not possible at all.


(system) #5