Elasticsearch从查询字符串返回国家/地区

时间:2014-10-05 18:56:51

标签: elasticsearch

我的索引中有一种国家/地区类型,其中包含国家/地区名称列表。我想找到用户可能在其查询中添加的任何国家/地区名称。例如,如果用户搜索:

car dealerships in japan

然后我想回国日本。如果我做了类似的事情,这适用于单字国家/地区:

GET /my_index/country/_search
{
  "query": {
        "match" : {
            "name": {
                  "query": "car dealerships in japan"
            }
        }

    }
}

返回国家日本,这就是我想做的事情。

但是如果国名中有多个单词,我不确定怎么会这样才能识别出来。否则,如果查询类似于:

car dealerships in the united kingdom

它将返回多个国家,如美国,英国,阿拉伯联合酋长国...但我希望它只返回联合王国进行此查询。

我不确定解决此问题的最佳方法。

1 个答案:

答案 0 :(得分:1)

我建议尝试使用Elasticsearch的同义词功能。作为一个简单的原因,请考虑您的用户不会一直使用“美国”,或者在他们的查询中始终使用“联合王国”。如果用户使用“USA”或“u s a”或“the states”或“england”,该怎么办?对于这些情况,您可以使用此功能。

这是一个起点:

{
  "settings": {
    "analysis": {
      "filter": {
        "my_synonym_filter": {
          "type": "synonym",
          "synonyms": [
            "u s a,united states,united states of america => usa",
            "g b,gb,great britain,united kingdom, uk, u k => britain,england,scotland,wales",
            "united arab emirates, emirates, arab emirates => emirates"
          ]
        }
      },
      "analyzer": {
        "my_synonyms": {
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "my_synonym_filter"
          ]
        }
      }
    }
  },
  "mappings": {
    "country": {
      "properties": {
        "name": {
          "type": "string",
          "analyzer": "my_synonyms"
        }
      }
    }
  }
}

并且,考虑到您所在国家/地区的这些国家/地区指数:

{ "index": {}}
{ "name": "japan"}
{ "index": {}}
{ "name": "united kingdom"}
{ "index": {}}
{ "name": "united states"}
{ "index": {}}
{ "name": "united arab emirates"}

搜索

{
  "query": {
    "match": {
      "name": {
        "query": "car dealerships in the uk, japan and emirates"
      }
    }
  }
}

会给你所有三个国家:

  "hits": [
     {
        "_index": "my_index",
        "_type": "country",
        "_id": "CMZe2ygBS4OLL3_lT_B2_Q",
        "_score": 0.03739948,
        "_source": {
           "name": "japan"
        }
     },
     {
        "_index": "my_index",
        "_type": "country",
        "_id": "T-e7rg_rTx-3rtTJYxJrBg",
        "_score": 0.03739948,
        "_source": {
           "name": "united arab emirates"
        }
     },
     {
        "_index": "my_index",
        "_type": "country",
        "_id": "EqlMu2RiRiSdwyqJa2nyzA",
        "_score": 0.017334092,
        "_source": {
           "name": "united kingdom"
        }
     }
  ]

如果您只查询一个国家/地区,则只会返回一个国家/地区:

{
  "query": {
    "match": {
      "name": {
        "query": "car dealerships in the united states"
      }
    }
  }
}

有关此功能的更多信息here