首页 > 解决方案 > 如何在 Elasticsearch 中存储国家/州/城市信息

问题描述

如何在 Elasticsearch 中存储国家/州/城市信息

i.e there are many countries
each country has many states
each state has many cities

它更容易存储在关系数据库中,但是如果我想存储所有可能的组合,我应该如何在 Elasticsearch 中执行此操作

我想将国家、州、城市位置存储在包含用户信息的某个索引中

i.e users (first_name, last_name, country, state, city ...)

标签: elasticsearchspring-data-elasticsearch

解决方案


请不要将 Elasticsearch 与 RDBMS 混淆,因为您没有提到您的用例是什么,即它的全文搜索或聚合,我将向您展示如何使用您的数据实现全文搜索,并且它很容易实现和不需要太多的配置/复杂性来实现它。

由于一个用户一次只能停留在一个城市、州和国家/地区,但如果您想为用户存储多个选项,也可以这样做,您只需索引,分离的值。

如果您需要这些字段的聚合,请索引这些字段,keyword以便您可以对其进行聚合。

全文搜索的完整示例

索引映射

{
  "mappings" :{
      "properties" :{
          "first_name" :{
              "type" : "text"
          },
          "last_name" :{
              "type" : "text"
          },
          "country" :{
              "type" : "text"
          },
          "state" :{
              "type" : "text"
          },
          "city" :{
              "type" : "text"
          }
      }
  }
}

索引示例文档

{
  "first_name" : "abc",
  "last_name" : "xyz",
  "country": "USA",
  "state" : "California",
  "city" : "SF"
}
{
  "first_name" : "opster",
  "last_name" : "ninja",
  "country": "Israel",
  "state" : "na",
  "city" : "tel aviv"
}
{
  "first_name" : "abc",
  "last_name" : "xyz",
  "country": "USA",
  "state" : "California, washintion", // not two state
  "city" : "SF"
}

现在搜索California将返回第一个和第三个文档,如下所示

{
    "query": {
        "match": {
            "state": "california"
        }
    }
}

和搜索结果

 "hits": [
            {
                "_index": "so_63601020",
                "_type": "_doc",
                "_id": "3",
                "_score": 0.38845783,
                "_source": {
                    "first_name": "abc",
                    "last_name": "xyz",
                    "country": "USA",
                    "state": "California",
                    "city": "SF"
                }
            },
            {
                "_index": "so_63601020",
                "_type": "_doc",
                "_id": "2",
                "_score": 0.2863813,
                "_source": {
                    "first_name": "foo",
                    "last_name": "bar",
                    "country": "USA",
                    "state": "California, washington",
                    "city": "SF"
                }
            }
        ]

推荐阅读