Find one term result, or a list of match results

Hi there :wave:

Sorry, this is undoubtedly a bit of noob question but I am still trying to get to grips with compound queries in Elasticsearch.

In my example, each document has a name field and we can assume that each name field is unique. The mapping is as follows (there's also an id field that I've excluded for brevity):

{
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "fields": {
          "exact": { 
            "type":  "keyword"
          }
        }
      }
    }
  }
}

I am wondering how to go about the following as a single query:

Perform a keyword match query on the name field to find one result. If that query doesn't find any results, perform a match query on the name field to return a list of similar results.

In other words, find one exact result OR find a list of similar results.

My first attempt was pretty naive, this obviously returns the exact match if present AND similar results:

{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "name.exact": "Acme Incorporated"
          }
        },
        {
          "match": {
            "name": "Acme Incorporated"
          }
        }
      ]
    }
  }
}

Any advice would be greatly appreciated :slight_smile: Thanks!

I did some more reading and I guess that another approach would be to use _mmatch to perform two separate queries, and pick and choose as required. This will work for my use case but I'm not sure if that's really the best approach so I am all ears on that :slight_smile:

I've decided to go with the Multi Search approach. In this case the first query will be the same keyword-based term query on the name field to attempt to find an exact match.

For the second query, I'll perform a match query, but I will also explicitly exclude possible exact results with must_not. Something like:

{
	"query": {
		"bool": {
			"must": {
				"match": {
					"name": "Acme Incorporated"
				}
			},
			"must_not": {
				"term": {
					"name.exact": "Acme Incorporated"
				}
			}
		}
	}
}

I can then decide at application level what to do with the results.

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