本篇文章给大家分享的是有关将唐诗三百首写入 Elasticsearch 会发生什么,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
创新互联专注于企业全网营销推广、网站重做改版、沙县网站定制设计、自适应品牌网站建设、成都h5网站建设、商城网站定制开发、集团公司官网建设、外贸网站建设、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为沙县等各大城市提供网站开发制作服务。
将唐诗三百首写入Elasticsearch会发生什么?
此项目是根据实战项目浓缩的一个小项目,几乎涵盖之前讲解的所有知识点。
通过这个项目的实战,能让你串联起之前的知识点应用于实战,并建立起需求分析、整体设计、数据建模、ingest管道使用、检索/聚合选型、kibana可视化分析等的全局认知。
数据来源:https://github.com/xuchunyang/300
注意数据源bug: 第1753行种的"id":178 需要手动改成 "id": 252。
注意:
注意:
检索分析DSL实战
聚合分析实战及可视化实战
本着:编码之前,设计先行的原则。
开发人员的通病——新的项目拿到需求以后,不论其简单还是复杂,都要先梳理需求,整理出其逻辑架构,优先设计,以便建立全局认知,而不是上来就动手敲代码。
本项目的核心知识点涵盖如下几块内容
有图有真相。

根据需求梳理出如下的逻辑架构,实际开发中要谨记如下的数据流向。
之前也有讲述,这里再强调一下数据建模的重要性。
数据模型支撑了系统和数据,系统和数据支撑了业务系统。
一个好的数据模型:
对于Elasticsearch的数据建模的核心是Mapping的构建。
对于原始json数据:
"id": 251, "contents": "打起黄莺儿,莫教枝上啼。啼时惊妾梦,不得到辽西。", "type": "五言绝句", "author": "金昌绪", "title": "春怨"
我们的建模逻辑如下:
| 字段名称 | 字段类型 | 备注说明 |
|---|---|---|
| _id | 对应自增id | |
| contents | text & keyword | 涉及分词,注意开启:fielddata:true |
| type | text & keyword | |
| author | text & keyword | |
| title | text & keyword | |
| timestamp | date | 代表插入时间 |
| cont_length | long | contents长度, 排序用 |
由于涉及中文分词,选型分词器很重要。
这里依然推荐:选择ik分词。
ik词典的选择建议:自带词典不完备,网上搜索互联网的一些常用语词典、行业词典如(诗词相关词典)作为补充完善。
创建:indexed_at 的管道,目的:
PUT _ingest/pipeline/indexed_at{ "description": "Adds timestamp to documents", "processors": [ { "set": { "field": "_source.timestamp", "value": "{{_ingest.timestamp}}" } }, { "script": { "source": "ctx.cont_length = ctx.contents.length();" } } ]}
如下DSL,分别构建了模板:my_template。
指定了settings、别名、mapping的基础设置。
模板的好处和便捷性,在之前的章节中有过详细讲解。
PUT _template/my_template{"index_patterns": ["some_index*"],"aliases": {"some_index": {}},"settings": {"index.default_pipeline": "indexed_at","number_of_replicas": 1,"refresh_interval": "30s"},"mappings": {"properties": {"cont_length":{"type":"long"},"author": {"type": "text","fields": {"field": {"type": "keyword"}},"analyzer": "ik_max_word"},"contents": {"type": "text","fields": {"field": {"type": "keyword"}},"analyzer": "ik_max_word","fielddata": true},"timestamp": {"type": "date"},"title": {"type": "text","fields": {"field": {"type": "keyword"}},"analyzer": "ik_max_word"},"type": {"type": "text","fields": {"field": {"type": "keyword"}},"analyzer": "ik_max_word"}}}}PUT some_index_01
通过如下的python代码实现。注意:
def read_and_write_index():# define an empty list for the Elasticsearch docsdoc_list = []# use Python's enumerate() function to iterate over list of doc stringsinput_file = open('300.json', encoding="utf8", errors='ignore')json_array = json.load(input_file)for item in json_array:try:# convert the string to a dict object# add a new field to the Elasticsearch docdict_doc = {}# add a dict key called "_id" if you'd like to specify an ID for the docdict_doc["_id"] = item['id']dict_doc["contents"] = item['contents']dict_doc["type"] = item['type']dict_doc["author"] = item['author']dict_doc["title"] = item['title']# append the dict object to the list []doc_list += [dict_doc]except json.decoder.JSONDecodeError as err:# print the errorsprint("ERROR for num:", item['id'], "-- JSONDecodeError:", err, "for doc:", dict_doc)print("Dict docs length:", len(doc_list))try:print ("\nAttempting to index the list of docs using helpers.bulk()")# use the helpers library's Bulk API to index list of Elasticsearch docsresp = helpers.bulk(client,doc_list,index = "some_index",doc_type = "_doc")# print the response returned by Elasticsearchprint ("helpers.bulk() RESPONSE:", resp)print ("helpers.bulk() RESPONSE:", json.dumps(resp, indent=4))except Exception as err:# print any errors returned w## Prerequisiteshile making the helpers.bulk() API callprint("Elasticsearch helpers.bulk() ERROR:", err)quit()
GET some_index/_search{"query": {"match": {"contents": "铭"}}}GET some_index/_search{"query": {"match": {"contents": "毅"}}}GET some_index/_search{"query": {"match": {"contents": "天下"}}}
实践表明:
不禁感叹:唐诗先贤们也是心怀天下,忧国忧民啊!
POST some_index/_search{"query": {"match_phrase": {"author": "李白"}},"sort": [{"cont_length": {"order": "desc"}}]}POST some_index/_search{"aggs": {"genres": {"terms": {"field": "author.keyword"}}}}
唐诗三百首中,李白共33首诗(仅次于杜甫39首),最长的是“蜀道难”,共:353 个字符。
李白、杜甫不愧为:诗仙和诗圣啊!也都是高产诗人!
POST some_index/_search{"sort": [{"cont_length": {"order": "desc"}}]}POST some_index/_search{"sort": [{"cont_length": {"order": "asc"}}]}
最长的诗:白居易-长恨歌-960个字符。
最短的诗:王维-鹿柴- 24个字符(并列的非常多)。
以下的截图通过kibana实现。细节在之前的kibana可视化中都有过讲解。





以上就是将唐诗三百首写入 Elasticsearch 会发生什么,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联行业资讯频道。
Copyright © 2009-2022 www.wtcwzsj.com 青羊区广皓图文设计工作室(个体工商户) 版权所有 蜀ICP备19037934号