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

标签 elasticsearch spring-data-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 ...)

最佳答案

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

因为一个用户一次只能停留在一个城市、州和国家,但如果您想为用户存储多个选项,这也是可以做到的,您只需要索引 分隔值。

如果您需要对这些字段进行聚合,请将这些字段索引为关键字,以便您可以对其进行聚合。

全文搜索的完整示例

索引映射

{
  "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"
                }
            }
        ]

关于elasticsearch - 如何在 Elasticsearch 中存储国家/州/城市信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63601020/

相关文章:

elasticsearch - Elasticsearch按选定的聚合值过滤数据

elasticsearch - 从 FTP 收集日志文件到 Logstash/Elasticsearch

java - 如何在 sql-server 数据库表上构建自由流搜索?

ElasticSearch 聚合 - 过滤和分组依据

spring data elasticsearch错误页面totalPages

spring - 使用包含下划线的字段使用 Spring Data Elasticsearch 查询 Elasticsearch

java - ElasticSearch 7 中的运算符 IN

elasticsearch - 弹性索引/search_analyzer匹配所有 token

maven - 将Elasticsearch数据文件夹移动到Maven目标

elasticsearch - Spring Data支持的ElasticSearch版本