Elasticsearch 数据建模-应用层联接

2020-09-05  本文已影响0人  觉释

应用层联接

我们通过在我们的应用程序中实现联接可以(部分)模拟关系数据库。 例如,比方说我们正在对用户和他们的博客文章进行索引。在关系世界中,我们会这样来操作:

PUT my_index/_doc/1 
{
  "name":     "John Smith",
  "email":    "john@smith.com",
  "dob":      "1970/10/24"
}

POST my_index_b/_doc/2 
{
  "title":    "Relationships",
  "body":     "It's complicated...",
  "user":     1 
}

每个文档的 index, type, 和 id 一起构造成主键。

通过用户的 id 链接到用户。index 和 type 并不需要因为在我们的应用程序中已经硬编码。

通过用户的 ID 1 可以很容易的找到博客帖子。

GET /my_index_b/_search
{
  "query": {
    "bool": {
      "filter": {
        "term": { "user": 1 }
      }
    }
  }
}



GET /my_index/_search
{
  "query": {
    "match": {
      "name": "John"
    }
  }
}


GET /my_index_b/_search
{
  "query": {
    "bool": {
      "filter": {
        "terms": { "user": [1] }  
      }
    }
  }
}

非规范化你的数据

PUT /my_index/_doc/1
{
  "name":     "John Smith",
  "email":    "john@smith.com",
  "dob":      "1970/10/24"
}

PUT /my_index/_doc/2
{
  "title":    "Relationships",
  "body":     "It's complicated...",
  "user":     {
    "id":       1,
    "name":     "John Smith" 
  }
}


GET /my_index/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "title":     "relationships" }},
        { "match": { "user.name": "John"          }}
      ]
    }
  }
}

字段折叠

一个普遍的需求是需要通过特定字段进行分组。例如我们需要按照用户名称 分组 返回最相关的博客文章。 按照用户名分组意味着进行 terms 聚合。 为能够按照用户 整体 名称进行分组,名称字段应保持 not_analyzed 的形式, 具体说明参考 聚合与分析:

PUT /my_index/_mapping
{
  "properties": {
    "user": {
      "properties": {
        "name": { 
          "type": "text",
          "fields": {
            "raw": { 
              "type":  "keyword"
              
            }
          }
        }
      }
    }
  }
}

PUT /my_index/_doc/1
{
  "name": "John Smith",
  "email": "john@smith.com",
  "dob": "1970/10/24"
}

PUT /my_index_b/_doc/2
{
  "title": "Relationships",
  "body": "It's complicated...",
  "user": {
    "id": 1,
    "name": "John Smith"
  }
}

PUT /my_index/_doc/3
{
  "name": "Alice John",
  "email": "alice@john.com",
  "dob": "1979/01/04"
}
PUT /my_index_b/_doc/4
{
  "title": "Relationships are cool",
  "body": "It's not complicated at all...",
  "user": {
    "id": 3,
    "name": "Alice John"
  }
}
 
 
 
 GET /my_index_b/_search
{
  "size" : 10, 
  "query": { 
    "bool": {
      "must": [
        { "match": { "title":     "relationships" }},
        { "match": { "user.name": "John"          }}
      ]
    }
  },
  "aggs": {
    "users": {
      "terms": {
        "field":   "user.name.keyword",      
        "order": { "top_score": "desc" } 
      },
      "aggs": {
        "top_score": { "max":      { "script":  "_score"           }}, 
        "blogposts": { "top_hits": { "_source": "title", "size": 5 }}  
      }
    }
  }
}
上一篇 下一篇

猜你喜欢

热点阅读