1、构造冗余的用户和博客数据
第二种建模方式:用冗余数据,采用文档数据模型,进行数据建模,实现用户和博客的关联
PUT /website/users/1 { "name": "小鱼儿", "email": "[email protected]", "birthday": "1980-01-01" }
PUT /website/blogs/1 { "title": "小鱼儿的第一篇博客", "content": "大家好,我是小鱼儿。。。", "userInfo": { "userId": 1, "username": "小鱼儿" } }
|
冗余数据,就是说,将可能会进行搜索的条件和要搜索的数据,放在一个doc中
2、基于冗余用户数据搜索博客
GET /website/blogs/_search { "query": { "term": { "userInfo.username.keyword": { "value": "小鱼儿" } } } } 结果: { "took": 14, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 1, "max_score": 0.2876821, "hits": [ { "_index": "website", "_type": "blogs", "_id": "1", "_score": 0.2876821, "_source": { "title": "小鱼儿的第一篇博客", "content": "大家好,我是小鱼儿。。。", "userInfo": { "userId": 1, "username": "小鱼儿" } } } ] } } |
就不需要走应用层的join,先搜一个数据,找到id,再去搜另一份数据
直接走一个有冗余数据的type即可,指定要的搜索条件,即可搜索出自己想要的数据来
3、优点和缺点
优点:性能高,不需要执行两次搜索
缺点:数据冗余,维护成本高 --> 每次如果你的username变化了,同时要更新user type和blog type
一般来说,对于es这种NoSQL类型的数据存储来讲,都是冗余模式....
当然,你要去维护数据的关联关系,也是很有必要的,所以一旦出现冗余数据的修改,必须记得将所有关联的数据全部更新