nrs
nrs

Reputation: 945

How to perform Exact and partial match in elasticsearch?

Here is the json:

{
"took": 3,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 2,
"max_score": 1,
"hits": [
{
"_index": "testing",
"_type": "skills",
"_id": "AV9FMnRfkEZ90S4dhzF6",
"_score": 1,
"_source": {
"skill": "java"
}
}
,
{
"_index": "testing",
"_type": "skills",
"_id": "AV9FM777kEZ90S4dhzF7",
"_score": 1,
"_source": {
"skill": "c language"
}
}
]
}
}

I have two dcuments and i need to get the partial and exact matching skills.

partial match:

Suppose if i give "c" then i should get the result "c language" skill.

Input: c -> c language

Exact match:

Suppose if i give "java" then i should get the result "java" skill.

Input: java -> java

Upvotes: 0

Views: 726

Answers (1)

Hatim Stovewala
Hatim Stovewala

Reputation: 1251

Try this. Define your mapping by:

PUT index
{
  "mappings": {
    "type": {
      "properties": {
        "skill": {
          "type": "string",
          "index" : "analyzed",
          "fields": {
            "keyword": {
              "type": "string",
              "index" : "not_analyzed"
            }
          }
        }
      }
    }
  }
}

CURL equivalent for above command:

curl -XPUT localhost:9200/index -d '
{
  "mappings": {
    "type": {
      "properties": {
        "skill": {
          "type": "string",
          "index" : "analyzed",
          "fields": {
            "keyword": {
              "type": "string",
              "index" : "not_analyzed"
            }
          }
        }
      }
    }
  }
}'

Add documents:

POST index/type
{
  "skill":"c language"
}

POST index/type
{
  "skill":"java"
}

CURL equivalent for above commands:

curl -XPOST localhost:9200/index/type -d '
{
  "skill":"c language"
}'

curl -XPOST localhost:9200/index/type -d '
{
  "skill":"java"
}'

Search your documents:

Partial match:

GET index/_search
{
  "query": {
    "match": {
      "skill": "c"
    }
  }
}

Exact match:

GET index/_search
{
  "query": {
    "term": {
      "skill.keyword": "java"
    }
  }
}

CURL equivalent for above commands:

curl -XGET localhost:9200/index/_search -d '
{
  "query": {
    "match": {
      "skill": "c"
    }
  }
}'


curl -XGET localhost:9200/index/_search -d '
{
  "query": {
    "term": {
      "skill.keyword": "java"
    }
  }
}'

Upvotes: 1

Related Questions