Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does multi field mapping work in Elastic Search

I want to support both text search (match query) as well as exact match (term query) on a single field in my elasticsearch index.

Following is the mapping that I have created:

PUT multi_mapping_test/_mapping
{
  "properties": {
    "name": {
      "type": "text",
      "fields": {
        "keyword": {
          "type": "keyword"
        }
      }
    }
  }
}

However, the term query is not behaving as I am expecting it to (may be understanding of it is wrong).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For example, here are couple of sample documents indexed:

POST multi_mapping_test/_doc
{
  "name": "abc llc"
}

POST multi_mapping_test/_doc
{
  "name": "def llc"
}

Following term query yields no results:

GET multi_mapping_test/_search
{
  "query": {
    "term": {
      "name": {
        "value": "abc llc"
      }
    }
  }
}

Am I doing anything wrong or is my understanding of exact matches with term query incorrect?

P.S. The term query works fine when I put mapping for only keyword type.

>Solution :

Term query: Returns documents that contain an exact term in a provided field.
When you’re searching for exact match you should use keyword field types. Like the following:

GET multi_mapping_test/_search
{
  "query": {
    "term": {
      "name.keyword": {
        "value": "abc llc"
      }
    }
  }
}

In addition, You can use bool query for both text search (match query) and exact match (term query) in your elasticsearch index.

GET multi_mapping_test/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "name": "abc llc"
          }
        },
        {
          "term": {
            "name.keyword": {
              "value": "abc llc"
            }
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}

Note: You can also use the match_bool_prefix query if you need to autocomplete the feature.
Details: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-bool-prefix-query.html

enter image description here

"abc llc" _score will be higher than "def llc" because it matches both match and term queries.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading