Search code examples
phpelasticsearchfull-text-searchsearch-engine

How to use elasticsearch to search for 2 strings at once?


I'm trying to use elasticsearch to find multiple terms at once.

More specifically, when a user enters a search term like "quake 2", I want elasticsearch to match "quake 2" and "quake ii". So that it matches the result if the games is stored in the system with roman numerals.

I will be using PHP to detect when integers exist in the search term, and then generate the it's counterpart with the roman numerals included, which should be straight forward, so I wasn't looking for help with that.

It's when it comes down to doing the lookup of two strings at once using elasticsearch where I hit a brick wall.

Here's an example of what I've tried:

$json = '{
            "query" : {
                    "terms" : {
                        "title" : [ "quake", "crysis" ],
                        "minimum_should_match" : 1
                    }
                }
            }
        }';
$searchParams['index'] = 'thegamesdb';
$searchParams['type']  = 'game';
$searchParams['body'] = $json;
$elasticResults = $client->search($searchParams);

The above behaves as expected and returns a list of results that include quake and halo, with fairly sane seaach scores for each.

But when I attempt to use the above query to search for "quake 2" and "quake ii" at the same time, I get absolutely no hits? In fact I've determined that it seems to be the inclusion of the spaces between the title and number that is throwing elastic search off.

$json = '{
            "query" : {
                    "terms" : {
                        "title" : [ "quake 2", "quake ii" ],
                        "minimum_should_match" : 1
                    }
                }
            }
        }';

If spaces aren't allowed in a "terms" query, then how am I supposed to be performing this type of search?


Solution

  • Split the query into two.use bool query should condition and match query to get appropriate result. match query works because the match query are analyzed and constructed again by ES.

         {
        "query": {
            "bool": {
                "must": [
                   {
                       "match": {
                          "title": "quake 2"
                       }
                   },
                   {
                   "match": {
                      "title": "quake ii"
                   }
                   }
                ]
            }
            }
        }
    

    i ve tried it.. it worked.. HOpe it helps..!