How to exclude querystring reponse and keep only exact match if present?

How to return only exact match if exists else perform wildcard search. for e.g. for the below given set of data

    [
      {
        "_index" : "priority_test",
        "_type" : "_doc",
        "_id" : "3IkeZHUBYJCjRlSv-EXV",
        "_score" : 1.0,
        "_source" : {
          "number" : "GI#000001",
          "name" : "GI for Cost Center",
          "comments" : "Cost Center",
          "id" : "000001",
          "PlantCode" : "ABC"
        }
      },
      {
        "_index" : "priority_test",
        "_type" : "_doc",
        "_id" : "3YkeZHUBYJCjRlSv-EXV",
        "_score" : 1.0,
        "_source" : {
          "number" : "GI#0000010",
          "name" : "GI for WBS Element",
          "comments" : "WBS Element",
          "id" : "0000010",
          "PlantCode" : "XYZ"
        }
      },
      {
        "_index" : "priority_test",
        "_type" : "_doc",
        "_id" : "3okeZHUBYJCjRlSv-EXV",
        "_score" : 1.0,
        "_source" : {
          "number" : "GI#0000011",
          "name" : "GI for Cost Center & WBS Element",
          "comments" : "Cost Center & WBS Element",
          "id" : "0000011",
          "PlantCode" : "LMN"
        }
      },
      {
        "_index" : "priority_test",
        "_type" : "_doc",
        "_id" : "4IkeZHUBYJCjRlSv-EXV",
        "_score" : 1.0,
        "_source" : {
          "number" : "GI#00000100",
          "name" : "Manage Pick List GI",
          "comments" : "Manage Pick List GI",
          "id" : "00000100",
          "PlantCode" : "QRS"
        }
      }
    ]

In the above data, If i search for "GI#000001" in document number, The result must return only that document, otherwise it should perform a contains search that starts with "GI#000001*".

I've formed a query with looks something like the following:

    {
  "query": {
    "bool": {
      "should": [
        {
          "terms": {
            "number.keyword": [
              "GI#000001"
            ]
          }
        },
        {
          "query_string": {
            "fields": [
              "number.keyword"
            ],
            "query": """GI\#000001*"""
          }
        }
      ]
    }
  }
}

But the above query always returns a result even if there is an exact match available for "GI#000001".

Please guide me in building this search

I'd probably use the multi search API (which means 2 searches) and on the client side, I'd deal with the use case.
So you will get every time 2 responses.

If you know in advance that in most cases, the second query is not needed, I'd just call the first query and if empty call the second.

My 2 cents.

1 Like

Interesting, @dadoonet - we could be more efficient if we had a new fail-if query on the second backup search to cut it short if it looks like the primary search is working out.

1 Like

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