douyueqing1530
2014-03-19 15:55 阅读 84
已采纳

如何使用elasticsearch一次搜索2个字符串?

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dongshetao1814 dongshetao1814 2014-03-19 16:52

    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..!

    点赞 2 评论 复制链接分享
  • dpwo36915 dpwo36915 2014-03-19 16:35

    Have you tried using

    "terms" : {
        "title" : [ "quake", "2", "ii" ],
        "minimum_should_match" : 2
    }
    

    Or is that being a bit naive?

    点赞 7 评论 复制链接分享

相关推荐