douyueqing1530 2014-03-19 07:55
浏览 106
已采纳

如何使用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 2014-03-19 08: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..!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部