Lay András
Lay András

Reputation: 855

Match all partial words in one field

I have this query:

{
    "query": {
        "match": {
            "tag": {
                "query": "john smith",
                "operator": "and"
            }
        }
    }
}

With the and operator I solved to return documents, where words "john" and "smith" must be present in the tag field in any position and any order. But I need to return documents where all partial words must be present in the tag field, like "joh" and "smit". I try this:

{
    "query": {
        "match": {
            "tag": {
                "query": "*joh* *smit*",
                "operator": "and"
            }
        }
    }
}

but nothing returns. How can I solve this?

Upvotes: 0

Views: 34

Answers (1)

Amit
Amit

Reputation: 32376

You can use the edge_ngram tokenizer and boolean query with multiple must clause(using your example 2) to get the desired output.

Working example:

Index Def

{
  "settings": {
    "analysis": {
      "filter": {
        "autocomplete_filter": {
          "type": "edge_ngram", --> note this
          "min_gram": 1,
          "max_gram": 10
        }
      },
      "analyzer": {
        "autocomplete": { 
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "autocomplete_filter"
          ]
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "title": {
        "type": "text",
        "analyzer": "autocomplete", 
        "search_analyzer": "standard" 
      }
    }
  }
}

Index two sample doc, one which should match and one which shouldn't

{
   "title" : "john bravo" --> show;dn't match
}

{
   "title" : "john smith" --> should match
}

Boolean Search query with must clause

{
    "query": {
        "bool": {
            "must": [ --> this means both `jon` and `smit` match clause must match, replacement of your `and` operator.
                {
                    "match": {
                        "title": "joh"
                    }
                },
                {
                    "match": {
                        "title": "smit"
                    }
                }
            ]
        }
    }
}

Search result

"hits": [
         {
            "_index": "so_partial",
            "_type": "_doc",
            "_id": "1",
            "_score": 1.2840209,
            "_source": {
               "title": "john smith"
            }
         }
      ]

Upvotes: 1

Related Questions