Two kinds of search on a field?

Shahab :

I work on a project that uses elasticsearch 5.2. The code is in java and I use elasticsearch java client 5.2.

In this project, I have a field called hash, a 7-character code containing uppercase letters, lowercase letters, and numbers (in English language). I want to do two searches on this field:

  1. check the existence of a hash "ErTg1Qh" (case sensitive)

  2. find hashes that sub string s contains in them (for example, sub string "tg" exist in the hash "ErTg1Qh").

For the hash field, I chose the keyword datatype.

I used matchQuery function for first search as below:

String hash = "ErTg1Qh";    
QueryBuilders.matchQuery("hash", hash)

and queryStringQuery function for the second search as below:

queryString = "hash:*" + subString + "*";    
QueryBuilders.queryStringQuery(queryString)

but, the second one does not work properly.

How can I handle these two kinds of search on a field?

Opster ES Ninja Nishant :

One of your query requires to be case sensitive while the second one is case insensitive. So I'll suggest you to use sub field for the hash field. Your main field will be analyzed with lowercase analyzer and one will store raw data i.e. the exact hash. So your index will look like below:

PUT /test
{
  "settings": {
    "number_of_shards": "1",
    "number_of_replicas": "0",
    "analysis": {
      "analyzer": {
        "custom_lowercase": {
          "filter": [
            "lowercase"
          ],
          "type": "custom",
          "tokenizer": "keyword"
        }
      }
    }
  },
  "mappings": {
    "_doc": {
      "properties": {
        "hash": {
          "type": "text",
          "analyzer": "custom_lowercase",
          "fields": {
            "keyword": {
              "type": "keyword"
            }
          }
        }
      }
    }
  }
}

Query to check the existence of a hash "ErTg1Qh" (case sensitive)

POST /test/_doc/_search
{
  "query": {
    "match": {
      "hash.keyword": "ErTg1Qh"
    }
  }
}

Query to find hashes that sub string s contains in them

POST /test/_doc/_search
{
  "query": {
    "query_string": {
      "query": "*tg*"
    }
  }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=153200&siteId=1