以《刑法》文本.txt为例。

 

 

1,首先,ElasticSearch只能接收格式化的数据,所以,我们需要将文本文件转换为格式化的数据—json。

 下图为未处理的文本文件。

 

 

2,这里,使用python文件操作,将文本格式化为ElasticSearch可识别的json格式。

 

  1. #python 3.6
  2. #!/usr/bin/env python
  3.  
  4. # -*- coding:utf-8 -*-
  5. __author__ = 'BH8ANK'
  6. '''
  7. 最终将输出格式改为
  8. {"index":{"_index":"xingfa","_id":1}}
  9. {"text_entry":"犯罪的行为或者结果有一项发生在中华人民共和国领域内的,就认为是在中华人民共和国领域内犯罪。"}
  10. '''
  11.  
  12.  
  13. '''读取文件
  14. '''
  15. a = open(r"D:\xingfa.txt", "r",encoding='utf-8')
  16. out = a.read()
  17. #print(out)
  18. TypeList = out.split('\n')
  19. #print(TypeList)
  20. lenth = len(TypeList)
  21. print(lenth)
  22. number = 1
  23. ju_1 = '{"index":{"_index":"xingfa","_id":'
  24. ju_2 = '{"text_entry":"'
  25.  
  26. # print(ju_1)
  27. for x in TypeList:
  28. res_1 = ju_1 + str(number) + '}}'+'\n'
  29. print(res_1)
  30. a = open(r"D:\out.json", "a", encoding='UTF-8')
  31. a.write(res_1)
  32. res_2 = ju_2 + x + '"}'+'\n'
  33. print(res_2)
  34. a = open(r"D:\out.json", "a", encoding='UTF-8')
  35. a.write(res_2)
  36. a.close()
  37. number+=1

 

3,执行后,输出的json内容为:

 

 

 

  1. PUT /xingfa
  2. {
  3. "mappings": {
  4. "doc": {
  5. "properties": {
  6. "text_entry":{"type":"keyword"}
  7. }
  8. }
  9. }
  10. }

 

 

 

 

我们的ES组网情况如上图。

 

操作如下:

 

 命令如下:

  1. curl -H 'Content-Type: application/x-ndjson' -XPOST '10.0.0.19:9200/xingfa/doc/_bulk?pretty' --data-binary @out.json

 

等待命令执行完成后,即可登录kibana去查询对应的数据了。

 

使用查询语句:

  1. GET /xingfa/_search/
  2. {
  3. "query": { "match_all": {} },
  4. "size":"9999" //此处设置为9999,主要原因是,不加参数的话,默认搜索结果仅显示部分,一般是5.
  5. }

 

也可以直接在虚拟机命令行里,查询这个索引,确认数据是否已经完成上传。

 

使用查询语句:

  1. curl -XGET "http://10.0.0.19:9200/xingfa/_search/" -H 'Content-Type: application/json' -d'
  2. {
  3. "query": {
  4. "match_all": {}
  5. },
  6. "size": "9999"
  7. }'

 

 

 

至此,完成数据导入。

 

版权声明:本文为BH8ANK原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/BH8ANK/p/10496756.html