Mary
Mary

Reputation: 1145

In Elasticsearch, how do I perform a wildcard search with spaces?

I currently have an array of objects which includes:

        {
          "key": "party",
          "str_val": "THE TWITTER INC"
        }

and

        {
          "key": "party",
          "str_val": "twitter inc"
        }

The relevant part of my mapping is:

          "key": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "str_val": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }

When I try and perform a wildcard match as follows:

"wildcard": {
    "metadata.str_val": "*twitter*"
}

both of the documents are returned. But if I modify my query to include a space:

"wildcard": {
    "metadata.str_val": "*twitter inc*"
}

no documents are returned. How do I perform a wildcard search with spaces?

Upvotes: 0

Views: 1988

Answers (1)

Polynomial Proton
Polynomial Proton

Reputation: 5135

Option 1:

With your current mapping i.e without the use of an analyzer, query_string should work for you.

PUT my_index2/doc/1
{
  "key": "party",
  "str_val": "THE TWITTER INC"
}

PUT my_index2/doc/2
{
  "key": "party",
  "str_val": "twitter inc"
}

POST my_index2/_search
{
  "query": {
    "query_string": {
      "default_field": "str_val",
      "query": "*twitter inc*"
    }
  }
}

Option 2:

However, if you want to use wildcard, you need to add a custom analyzer as below:

PUT my_index/
{
  "settings": {
    "analysis": {
      "analyzer": {
        "k_lowercase": {
          "type": "custom",
          "tokenizer": "keyword",
          "filter": [
            "lowercase"
          ]
        }
      }
    }
  },
   "mappings": {
      "doc": {
        "properties": {
          "key": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }              
          },
          "str_val": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            },
             "analyzer":"k_lowercase"
          }
        }
      }
    }
}

Now add the records after putting the analyzer :

PUT my_index/doc/1
{
  "key": "party",
  "str_val": "THE TWITTER INC"
}

PUT my_index/doc/2
{
  "key": "party",
  "str_val": "twitter inc"
}

POST my_index/_search
{
  "query": {
    "wildcard": {
      "str_val": {
        "value": "*twitter inc*"
      }
    }
  }
}

Upvotes: 2

Related Questions