目录

一. 安装java环境与elasticsearch、kibana

​ 首先要求jdk为1.8及以上,这里elasticsearch(kibana同理,尽量保证elasticsearch版本一致,安装和启动方式也是一样的)版本采用6.5.4。

​ elasticsearch简介:https://baike.baidu.com/item/elasticsearch/3411206?fr=aladdin

​ elasticsearch官网:https://www.elastic.co/cn/downloads/

​ 点击下载,之后下拉选择历史版本past releases

​ 最后点击download即可

​ java环境配置看该博客:https://www.cnblogs.com/Neeo/articles/10368280.html

​ 安装完毕后如果没有出现错误,解压elasticsearch,然后进入其bin目录,双击打开其中的elasticsearch.bat文件即可,随后访问127.0.0.1:9200,如果能看到返回的json数据,代表配置成功。(其中9200是节点监听的断开,而9300是集群默认监听的端口)。

​ 未能正常启动原因

二. elasticsearch、kibana的部分文件说明

​ 1. 解压后的config中的elasticsearch.yml就是ES的配置文件,这用Notepad打开。

同目录的jvm.options是虚拟机jrel的配置。

同目录的log4j2.properties是日志的配置,可以配置日志的输出、级别等信息,一般不会修改。(log4j是Apache的一个框架,用于控制日志)

  1. Kibana目录下的config中的kibana.yml存放其配置文件。

三. Kibana的Dev tools中ES的简单命令

​ 数据准备

  1. PUT s18/doc/2
  2. {
  3. "name":"yangtao",
  4. "age": 18,
  5. "tags":"浪",
  6. "b":"19970521",
  7. "sex": "男"
  8. }
  9. PUT s18/doc/1
  10. {
  11. "name":"egon",
  12. "age": 20,
  13. "tags":"认真学习",
  14. "b":"19970781",
  15. "sex": "男"
  16. }
  17. PUT s18/doc/3
  18. {
  19. "name":"sybil",
  20. "age": 3,
  21. "tags":"认真学习",
  22. "b":"19971216",
  23. "sex": "女"
  24. }

  1. '索引/类型/文档' 的格式
  2. #增 PUT 如果PUT对的数据已存在,那么会进行更新的操作,但是PUT时传的参数是什么,更新之后的数据就是什么,所以需要填写所有的字段
  3. PUT s18/doc/1 #新增索引s18/doc/1 s18是_index,1是该数据的文档,doc是Type
  4. {
  5. "name":"sybil",
  6. "skill":"fly",
  7. "hobby":"sleep",
  8. "tags":"beautiful"
  9. }
  10. #删 DELETE
  11. DELETE s18 #删除索引(数据库)
  12. DELETE s18/doc/1 #删除索引s18下type是doc,文档是1的数据
  13. DELETE s18/doc/_search?q=tags:beautiful #这是错误的删除方式,要使用search的方式删除需要使用POST
  14. #查 GET
  15. GET s18/doc/1 #查文档为1的数据
  16. GET s18/doc/_search #查所有
  17. GET s18/doc/_search?q=name:sybil #查名字叫sybil的
  18. #更新指定字段POST,或配合search删除
  19. POST s18/doc/1/_update
  20. {
  21. "doc":{ # 需要指定type,相当于指定表名
  22. "tags":"美丽冻人"
  23. }
  24. }
  25. POST s18/doc/_delete_by_query?q=age:18 #删除年龄为18的数据,不过不推荐使用该方式
  26. #查询的两种方式
  27. 1.查询字符串 query string
  28. GET s18/doc/_search?q=age:18
  29. 2. DSL 结构化查询
  30. GET s18/doc/_search
  31. {
  32. "query":{
  33. "match":{
  34. "age":18
  35. }
  36. }
  37. }
  38. GET s18/doc/_search
  39. {
  40. "query":{
  41. "match_all":{} #因为是查所有,不需要参数
  42. }
  43. }
  1. GET s18/_mapping

  1. GET s18/_settings

  2. GET s18

四. ES的复杂查询

1.排序sort、分页、布尔查询bool

  1. #排序 sort 不是所有的字段都能排序,比如名字
  2. GET s18/doc/_search
  3. {
  4. "query":{
  5. "match_all":{}
  6. },
  7. "sort": [ #排序
  8. {
  9. "age":{
  10. "order": "asc" #升序,desc降序
  11. }
  12. }
  13. ]
  14. }
  15. #分页 内部会先排好序,保证翻页后不会出现已经返回过的数据
  16. GET s18/doc/_search
  17. {
  18. "query":{
  19. "match_all":{}
  20. },
  21. "from": 0, #从0条开始
  22. "size": 2 #返回2条数据
  23. }
  24. #布尔查询bool: should(or) must(and) must_not(not),must_not
  25. GET s18/doc/_search
  26. {
  27. "query": {
  28. "bool": {
  29. "should": [ #名字是sybil或者年龄18岁
  30. {
  31. "match": {
  32. "name": "sybil"
  33. }
  34. },
  35. {
  36. "match": {
  37. "age": "18"
  38. }
  39. }
  40. ]
  41. }
  42. }
  43. }
  44. '查询性别是男的,年龄18'
  45. GET s18/doc/_search
  46. {
  47. "query": {
  48. "bool":{
  49. "must": [
  50. {
  51. "match": {
  52. "age": "18"
  53. }
  54. },
  55. {
  56. "match": {
  57. "sex": "男"
  58. }
  59. }
  60. ]
  61. }
  62. }
  63. }
  64. #查询年龄大于19岁的男的 filter尽量用must配合,避免脏数据
  65. GET s18/doc/_search
  66. {
  67. "query": {
  68. "bool": {
  69. "must": [
  70. {"match": {
  71. "sex": "男"
  72. }}
  73. ],
  74. "filter": {
  75. "range": {
  76. "age": {
  77. "gte": 19,
  78. "lte": 20
  79. }
  80. }
  81. }
  82. }
  83. }
  84. }

2.高亮查询highlight

  1. #查询name是sybil的文档
  2. #高亮查询,查询name是sybil的文档,查询的结果需要在前端才能体现高亮,因为是标签的效果
  3. GET s18/doc/_search
  4. {
  5. "query": {
  6. "match": {
  7. "name": "sybil"
  8. }
  9. },
  10. "highlight": {
  11. "fields": {
  12. "name": {} #查询的结果用<em>标签包裹
  13. }
  14. }
  15. }
  16. GET s18/doc/_search
  17. {
  18. "query": {
  19. "match": {
  20. "name": "sybil" #会将我们这里定义的字段高亮显示
  21. }
  22. },
  23. "highlight": { #可以使用pre_tags与post_tags自定义标签
  24. "pre_tags": "<b style='color:red;font-size:20px'>",
  25. "post_tags": "<\b>",
  26. "fields": {
  27. "name": {} #这里指定字段后空着即可
  28. }
  29. }
  30. }

3.结果过滤_source

  1. #过滤出查询结果中想要的字段
  2. GET s18/doc/_search
  3. {
  4. "query": {
  5. "match": {
  6. "name": "sybil"
  7. }
  8. },
  9. "_source": "name" #单个字段
  10. }
  11. GET s18/doc/_search
  12. {
  13. "query": {
  14. "match": {
  15. "name": "sybil"
  16. }
  17. },
  18. "_source": ["name", "age"] #多个字段
  19. }

4.聚合查询

  1. #sum,查询所有男生的年龄
  2. GET s18/doc/_search
  3. {
  4. "query": {
  5. "match": {
  6. "sex": "男"
  7. }
  8. },
  9. "aggs": {
  10. "my_sum": { #这是查询结果的键,可以自定义
  11. "sum": { #这是聚合的方法
  12. "field": "age" #指定聚合的依据
  13. }
  14. }
  15. }
  16. }
  17. #查询最大年龄的男生
  18. GET s18/doc/_search
  19. {
  20. "query": {
  21. "match": {
  22. "sex": "男"
  23. }
  24. },
  25. "aggs": {
  26. "my_max": {
  27. "max": {
  28. "field": "age"
  29. }
  30. }
  31. }
  32. }
  33. #查询最小年龄的男生
  34. GET s18/doc/_search
  35. {
  36. "query": {
  37. "match": {
  38. "sex": "男"
  39. }
  40. },
  41. "aggs": {
  42. "my_min": {
  43. "min": {
  44. "field": "age"
  45. }
  46. }
  47. }
  48. }
  49. #查询男生的平均年龄
  50. GET s18/doc/_search
  51. {
  52. "query": {
  53. "match": {
  54. "sex": "男"
  55. }
  56. },
  57. "aggs": {
  58. "my_avg": {
  59. "avg": {
  60. "field": "age"
  61. }
  62. }
  63. }
  64. }
  65. #分组,根据年龄,0-10,,0-20
  66. GET s18/doc/_search
  67. {
  68. "query": {
  69. "match": {
  70. "sex": "男"
  71. }
  72. },
  73. "aggs": {
  74. "my_group": { #分组名称
  75. "range": {
  76. "field": "age",
  77. "ranges": [
  78. {
  79. "from": 0, #[0, 10)
  80. "to": 10
  81. },
  82. {
  83. "from": 10,
  84. "to": 20
  85. },
  86. {
  87. "from": 20,
  88. "to": 30
  89. }
  90. ]
  91. }
  92. }
  93. }
  94. }
  95. #分组,根据年龄,0-10,,0-20, 对每组年龄求和
  96. GET s18/doc/_search
  97. {
  98. "query": {
  99. "match": {
  100. "sex": "男"
  101. }
  102. },
  103. "aggs": {
  104. "my_group": {
  105. "range": {
  106. "field": "age",
  107. "ranges": [
  108. {
  109. "from": 0,
  110. "to": 10
  111. },
  112. {
  113. "from": 10,
  114. "to": 20
  115. },
  116. {
  117. "from": 20,
  118. "to": 30
  119. }
  120. ]
  121. },
  122. "aggs": {
  123. "my_sum": {
  124. "sum": {
  125. "field": "age"
  126. }
  127. }
  128. }
  129. }
  130. }
  131. }

5. ES的mapping映射

  1. #自定义索引的映射
  2. PUT s2
  3. {
  4. "mappings": {
  5. "doc":{ #类型
  6. "properties":{ #文档的属性
  7. "name":{
  8. "type":"text"
  9. },
  10. "age":{
  11. "type":"long"
  12. },
  13. "desc":{
  14. "type":"text"
  15. }
  16. }
  17. }
  18. }
  19. }
  20. #如果给该索引加文档时,额外增加了字段,那么mappings会自动增加该字段,使其能够成为查询条件
  21. GET s2/_mapping
  22. PUT s2/doc/2
  23. {
  24. "name":"catmao",
  25. "age":30,
  26. "desc":"beautiful",
  27. "skill":"sleep"
  28. }
  29. GET s2/_mapping #再次执行会发现字段多了skill
  30. #这是由mappings的dynamic的三种状态,三种状态时,均可以缺省字段
  31. dynamictrue时特征如上。
  32. dynamicfalse时,PUT添加的数据有额外字段时,Mapping不会自动添加,该字段也无法成为查询的条件。
  33. dynamicstrict时,添加的数据不能有额外的字段,会直接报错
  34. PUT s6
  35. {
  36. "mappings": {
  37. "doc":{
  38. "dynamic":"strict",
  39. "properties":{
  40. "name":{
  41. "type":"text"
  42. }
  43. }
  44. }
  45. }
  46. }
  47. #mapping的ignore_above,不会为超过该设定字符长度的字符串设定索引与存储,即无法成为有效的查询条件,仅对type为keyword的字段有效。
  48. https://www.cnblogs.com/Neeo/articles/10789701.html
  49. PUT s7
  50. {
  51. "mappings": {
  52. "doc":{
  53. "properties":{
  54. "title":{
  55. "type":"keyword",
  56. "ignore_above":10
  57. }
  58. }
  59. }
  60. }
  61. }
  62. PUT s7/doc/2
  63. {
  64. "title":"从手机、平板电脑、路由器"
  65. }
  66. PUT s7/doc/1
  67. {
  68. "title":"1234567"
  69. }
  70. GET s7/doc/_search
  71. {
  72. "query": {
  73. "match": {
  74. "title": "1234567"
  75. }
  76. }
  77. }
  78. #mappings参数之index,设置为false后,ES不会为该字段建立索引,其实是不会做分词
  79. #mappings的index参数
  80. PUT s8
  81. {
  82. "mappings": {
  83. "doc":{
  84. "properties":{
  85. "t1":{
  86. "type":"text",
  87. "index":"true"
  88. },
  89. "t2":{
  90. "type":"text",
  91. "index":"false"
  92. }
  93. }
  94. }
  95. }
  96. }
  97. PUT s8/doc/1
  98. {
  99. "t1":"论母猪的厂前保养",
  100. "t2":"论母猪的厂后保养"
  101. }
  102. GET s8/doc/_search
  103. {
  104. "query": {
  105. "match": {
  106. "t2": "母猪"
  107. }
  108. }
  109. }
  110. #mappings的copy_to,把一个字段的值复制给另一个,可以减少一次查询的次数
  111. PUT s9
  112. {
  113. "mappings": {
  114. "doc":{
  115. "properties":{
  116. "t1":{
  117. "type":"text",
  118. "copy_to":"full_name" #复制给多个字段 ["f1", "f2"]
  119. },
  120. "t2":{
  121. "type":"text",
  122. "copy_to":"full_name"
  123. },
  124. "full_name":{
  125. "type":"text"
  126. }
  127. }
  128. }
  129. }
  130. }
  131. PUT s9/doc/1
  132. {
  133. "t1":"xxx",
  134. "t2":"ooo"
  135. }
  136. GET s9/doc/_search
  137. {
  138. "query": {
  139. "match": {
  140. "full_name": "xxx"
  141. }
  142. }
  143. }

6.嵌套属性

  1. #嵌套类型
  2. PUT w1
  3. {
  4. "mappings": {
  5. "doc":{
  6. "properties":{
  7. "name":{
  8. "type":"text"
  9. },
  10. "age":{
  11. "type":"long"
  12. },
  13. "info":{ #info字段嵌套两个字段
  14. "properties":{
  15. "addr":{
  16. "type":"text"
  17. },
  18. "tel":{
  19. "type":"long"
  20. }
  21. }
  22. }
  23. }
  24. }
  25. }
  26. }
  27. PUT w1/doc/1 #插入一条数据
  28. {
  29. "name":"tom",
  30. "age":18,
  31. "info":{
  32. "addr":"北京",
  33. "tel":"10010"
  34. }
  35. }
  36. GET w1/doc/_search
  37. {
  38. "query": {
  39. "match": {
  40. "info.tel": "10010" #以嵌套字段的属性为查询条件时,直接点语法即可
  41. }
  42. }
  43. }

7.settings设置主从分片

  1. #主分片一旦设置无法更改,复制分片可以
  2. PUT w2
  3. {
  4. "mappings": {
  5. "doc":{
  6. "properties":{
  7. "title":{
  8. "type":"text"
  9. }
  10. }
  11. }
  12. },
  13. "settings": { #通过settings设置
  14. "number_of_shards": 3, #主分片数量,默认为5
  15. "number_of_replicas": 3 #复制分片数量,默认为1
  16. }
  17. }
  18. GET w2

8.match系列

博客地址https://www.cnblogs.com/Neeo/articles/10578482.html

  1. #数据准备
  2. PUT t1/doc/1
  3. {
  4. "title":"中国是世界上人口最多的国家"
  5. }
  6. PUT t1/doc/2
  7. {
  8. "title":"美国是世界上军事实力强大多的国家"
  9. }
  10. PUT t1/doc/3
  11. {
  12. "title":"北京是中国 的首都"
  13. }

​ 使用match查询“中国”

  1. #会发现美国也包含在其中,这是因为match内部会散列分词,内部是采用标准的分析器,中国会分为中和国
  2. GET t1/doc/_search
  3. {
  4. "query": {
  5. "match": {
  6. "title": "中国"
  7. }
  8. }
  9. }

​ 我们想把中国当成一个短语,需要采用match_phrase

  1. #这样就不好分词,把中国当成一个短语去查询
  2. GET t1/doc/_search
  3. {
  4. "query": {
  5. "match_phrase": {
  6. "title": "中国"
  7. "slop": 1 #该参数可以指定分词的间隔
  8. }
  9. }
  10. }

​ 最左前缀查询match_phrase_prefix

  1. PUT t2/doc/1
  2. {
  3. "title":"beautiful girl"
  4. }
  5. PUT t2/doc/2
  6. {
  7. "title":"beautiful so"
  8. }
  9. GET t2/doc/_search
  10. {
  11. "query": {
  12. "match_phrase_prefix": {
  13. "title": "bea" #只要有单词以bea开头
  14. }
  15. }
  16. }

​ multi_match多字段查询,可以完成match_phrase和match_phrase_prefix的工作,使用很灵活。

  1. PUT t3/doc/1
  2. {
  3. "t1":"beautiful girl",
  4. "t2":"beautiful so"
  5. }
  6. #查找字段t1和t2都包含beautiful的文档
  7. GET t3/doc/_search
  8. {
  9. "query": {
  10. "multi_match": {
  11. "query": "beautiful",
  12. "fields": ["t1", "t2"]
  13. }
  14. }
  15. }

五. elasticsearch分析数据的过程漫谈

详见博客https://www.cnblogs.com/Neeo/p/10304892.html,附带安装ik分词

5.1 ik安装的问题

5.2 ik分词的测试

  1. #ik分词的测试
  2. GET _analyze
  3. {
  4. "analyzer": "standard",
  5. "text":"上海自来水来自海上"
  6. }
  7. GET _analyze
  8. {
  9. "analyzer": "ik_smart",
  10. "text":"上海自来水来自海上"
  11. }
  12. #粒度更细,一般存储时建议使用粒度粗的(意义更大),ik_max_word会将文档做最细粒度的拆分
  13. GET _analyze
  14. {
  15. "analyzer": "ik_max_word",
  16. "text":"上海自来水来自海上"
  17. }

六. python操作Elasticsearch

6.1 python连接 ES

​ doc_type默认是doc,所以可以不写,不过建议都写上,以防万一

  1. '1. 安装elasticsearch模块'
  2. pip install elasticsearch
  3. # 豆瓣源
  4. pip install -i https://pypi.doubanio.com/simple/ elasticsearch
  5. '2. 连接的方式'
  6. from elasticsearch import Elasticsearch
  7. # es = Elasticsearch() # 默认连接本地elasticsearch
  8. # es = Elasticsearch(['127.0.0.1:9200']) # 连接本地9200端口
  9. es = Elasticsearch(
  10. ["192.168.1.10", "192.168.1.11", "192.168.1.12"], # 连接集群,以列表的形式存放各节点的IP地址
  11. sniff_on_start=True, # 连接前测试
  12. sniff_on_connection_fail=True, # 节点无响应时刷新节点
  13. sniff_timeout=60 # 设置超时时间
  14. )
  15. '3. 配置忽略响应状态码'
  16. es = Elasticsearch(['127.0.0.1:9200'],ignore=400) # 忽略返回的400状态码
  17. es = Elasticsearch(['127.0.0.1:9200'],ignore=[400, 405, 502]) # 以列表的形式忽略多个状态码
  18. '4. 简单的示例'
  19. from elasticsearch import Elasticsearch
  20. es = Elasticsearch() # 默认连接本地elasticsearch
  21. # print(es.ping()) #可以用该方法查看是否连接成功,如果群集已启动,则返回True,否则返回False
  22. print(es.index(index='p1', doc_type='doc', id=1, body={'name': "sybil", "age": 18})) #index方法,如果索引存在则更新,否则增加新记录
  23. print(es.get(index='p1', doc_type='doc', id=1))

6.2 python操作ES

  1. # search方法使用的较多,因为可以跟复杂查询
  2. '对返回的信息的几种过滤方法(过滤出想要显示的信息)'
  3. body = {
  4. "query": {
  5. "match": {
  6. "name": "lou22"
  7. }
  8. }
  9. }
  10. # 返回的是一个大字典
  11. print(es.search(index='p1', body=body))
  12. # 可以使用filter_path过滤出其中想要的信息
  13. print(es.search(index='p1', body=body, filter_path=['hits.hits']))
  14. # 查询出来的信息主要保存在_source中 {'hits': {'hits': [{'_source': {'name': 'lou22'}}]}}
  15. print(es.search(index='p1', body=body, filter_path=['hits.hits._source']))
  16. # 也可以指定多个要显示的信息 {'hits': {'total': 1, 'hits': [{'_source': {'name': 'lou22'}}]}}
  17. print(es.search(index='p1', body=body, filter_path=['hits.hits._source', 'hits.total']))
  18. # 可以用*指定返回hits下所有的内容 *是语法,表示所有
  19. print(es.search(index='p1', body=body, filter_path=['hits.*']))
  20. # 可以用*指定返回hits下的hits中所有的内容
  21. print(es.search(index='p1', body=body, filter_path=['hits.hits._*']))
  22. '过滤出结果中想要的字段,_source'
  23. print(es.search(index='py3', doc_type='doc', body={"query": {"match":{"age": 20}}})) # 一般查询
  24. print(es.search(index='py3', doc_type='doc', body={"query": {"match":{"age": 19}}},_source=['name', 'age'])) # 结果字段过滤
  25. print(es.search(index='py3', doc_type='doc', body={"query": {"match":{"age": 19}}},_source_exclude =[ 'age'])) #除了age字段之外的所有字段都要
  26. print(es.search(index='py3', doc_type='doc', body={"query": {"match":{"age": 19}}},_source_include =[ 'age'])) #只要age字段,同_source差不多

get_source直接返回数据字典

  1. # 直接返回数据字典 {'name': 'lou22'}
  2. print(es.get_source(index='p1', doc_type='doc', id=1))

count统计查询结果的个数

  1. # 新建几条数据
  2. for i in range(2, 11):
  3. print(es.index(index='p1', doc_type='doc', body={"name": "lou%s" % i}))
  4. # 指定用于查询的方式
  5. body = {
  6. "query": {
  7. "match": {
  8. "name": "lou2"
  9. }
  10. }
  11. }
  12. #查询回来的结果就是字典,可以采用字典的操作方式
  13. print(es.count(index='p1', doc_type='doc', body=body))['count'] # 1
  14. print(es.count(index='w2')) # {'count': 6, '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0}}
  15. print(es.count(index='w2', doc_type='doc')) # {'count': 6, '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0}}

es.create****创建索引(索引不存在的话)并新增一条数据,索引存在仅新增(只能新增,重复执行会报错

  1. #其实内部调用了es.index,一般不使用create方法
  2. print(es.create(index='py3', doc_type='doc', id='1', body={"name": '王五', "age": 20}))
  3. print(es.get(index='py3', doc_type='doc', id='1'))

es.deletees.delete_by_query

  1. #es.delete,删除指定的文档。比如删除文章id为4的文档,但不能删除索引,如果想要删除索引,还需要es.indices.delete来处理
  2. print(es.delete(index='py3', doc_type='doc', id='4'))
  3. #es.delete_by_query,删除与查询匹配的所有文档
  4. print(es.delete_by_query(index='py3', doc_type='doc', body={"query": {"match":{"age": 20}}}))

es.existses.info

  1. # es.exists,查询elasticsearch中是否存在指定的文档,返回一个布尔值
  2. print(es.exists(index='py3', doc_type='doc', id='1'))
  3. #es.info,获取当前集群的基本信息,一般使用kibana查看,因为比较直观
  4. print(es.info())

6.3 es.indices对索引的操作

es.indices.create****在Elasticsearch中创建索引,用的最多

  1. body = {
  2. "mappings": {
  3. "doc": {
  4. "dynamic": "strict", #设置严格模式
  5. "properties": {
  6. "title": {
  7. "type": "text",
  8. "analyzer": "ik_max_word"
  9. },
  10. "url": {
  11. "type": "text"
  12. },
  13. "action_type": {
  14. "type": "text"
  15. },
  16. "content": {
  17. "type": "text"
  18. }
  19. }
  20. }
  21. }
  22. }
  23. es.indices.create('py4', body=body)

es.indices.analyze,返回分词结果

  1. es.indices.analyze(body={'analyzer': "ik_max_word", "text": "皮特和茱丽当选“年度模范情侣”Brad Pitt and Angelina Jolie"})

es.indices.delete,在Elasticsearch中删除索引

  1. print(es.indices.delete(index='py4'))
  2. print(es.indices.delete(index='w3')) # {'acknowledged': True}

es.indices.put_alias,为一个或多个索引创建别名,查询多个索引的时候,可以使用这个别名

  1. print(es.indices.put_alias(index='py4', name='py4_alias')) # 为单个索引创建别名
  2. print(es.indices.put_alias(index=['py3', 'py2'], name='py23_alias')) # 为多个索引创建同一个别名,联查用

es.indices.delete_alias,删除一个或多个别名

  1. print(es.indices.delete_alias(index='alias1'))
  2. print(es.indices.delete_alias(index=['alias1, alias2']))

es.indices.get_mapping,检索索引或索引/类型的映射定义

  1. print(es.indices.get_mapping(index='py4'))

es.indices.get_settings,检索一个或多个(或所有)索引的设置

  1. print(es.indices.get_settings(index='py4'))

es.indices.get,允许检索有关一个或多个索引的信息

  1. print(es.indices.get(index='py2')) # 查询指定索引是否存在
  2. print(es.indices.get(index=['py2', 'py3']))

es.indices.get_alias,检索一个或多个别名

  1. print(es.indices.get_alias(index='py2'))
  2. print(es.indices.get_alias(index=['py2', 'py3']))

es.indices.get_field_mapping,检索特定字段的映射信息

  1. print(es.indices.get_field_mapping(fields='url', index='py4', doc_type='doc'))
  2. print(es.indices.get_field_mapping(fields=['url', 'title'], index='py4', doc_type='doc'))

其他

  1. # es.indices.delete_alias,删除特定别名。
  2. # es.indices.exists,返回一个布尔值,指示给定的索引是否存在。
  3. # es.indices.exists_type,检查索引/索引中是否存在类型/类型。
  4. # es.indices.flus,明确的刷新一个或多个索引。
  5. # es.indices.get_field_mapping,检索特定字段的映射。
  6. # es.indices.get_template,按名称检索索引模板。
  7. # es.indices.open,打开一个封闭的索引以使其可用于搜索。
  8. # es.indices.close,关闭索引以从群集中删除它的开销。封闭索引被阻 止进行读/写操作。
  9. # es.indices.clear_cache,清除与一个或多个索引关联的所有缓存或特定缓存。
  10. # es.indices.put_alias,为特定索引/索引创建别名。
  11. # es.indices.get_uprade,监控一个或多个索引的升级程度。
  12. # es.indices.put_mapping,注册特定类型的特定映射定义。
  13. # es.indices.put_settings,实时更改特定索引级别设置。
  14. # es.indices.put_template,创建一个索引模板,该模板将自动应用于创建的新索引。
  15. # es.indices.rollove,当现有索引被认为太大或太旧时,翻转索引API将别名转移到新索引。API接受单个别名和条件列表。别名必须仅指向单个索引。如果索引满足指定条件,则创建新索引并切换别名以指向新别名。
  16. # es.indices.segments,提供构建Lucene索引(分片级别)的低级别段信息

6.4 Cluster 集群相关

es.cluster.get_settigns,获取集群设置

  1. print(es.cluster.get_settings())

es.cluster.health,获取有关群集运行状况的非常简单的状态

  1. print(es.cluster.health())

es.cluster.state,获取整个集群的综合状态信息

  1. print(es.cluster.state())

es.cluster.stats,返回群集的当前节点的信息

  1. print(es.cluster.stats())

6.5 Node 节点相关

es.nodes.info,返回集群中节点的信息

  1. print(es.nodes.info()) # 返回所节点
  2. print(es.nodes.info(node_id='node1')) # 指定一个节点
  3. print(es.nodes.info(node_id=['node1', 'node2'])) # 指定多个节点列表

es.nodes.stats,获取集群中节点统计信息

  1. print(es.nodes.stats())
  2. print(es.nodes.stats(node_id='node1'))
  3. print(es.nodes.stats(node_id=['node1', 'node2']))

es.nodes.hot_threads,获取指定节点的线程信息

  1. print(es.nodes.hot_threads(node_id='node1'))
  2. print(es.nodes.hot_threads(node_id=['node1', 'node2']))

es.nodes.usage,获取集群中节点的功能使用信息

  1. print(es.nodes.usage())
  2. print(es.nodes.usage(node_id='node1'))
  3. print(es.nodes.usage(node_id=['node1', 'node2']))

6.6 Cat 一种查询方式

es.cat.aliases,返回别名信息

  1. #name要返回的以逗号分隔的别名列表。
  2. #formatAccept标头的简短版本,例如json,yaml
  3. print(es.cat.aliases(name='py23_alias'))
  4. print(es.cat.aliases(name='py23_alias', format='json'))

es.cat.allocation,返回分片使用情况

  1. print(es.cat.allocation())
  2. print(es.cat.allocation(node_id=['node1']))
  3. print(es.cat.allocation(node_id=['node1', 'node2'], format='json'))

es.cat.count,Count提供对整个群集或单个索引的文档计数的快速访问

  1. print(es.cat.count()) # 集群内的文档总数
  2. print(es.cat.count(index='py3')) # 指定索引文档总数
  3. print(es.cat.count(index=['py3', 'py2'], format='json')) # 返回两个索引文档和

es.cat.fielddata,基于每个节点显示有关当前加载的fielddata的信息。有些数据为了查询效率,会放在内存中,fielddata用来控制哪些数据应该被放在内存中,而这个es.cat.fielddata则查询现在哪些数据在内存中,数据大小等信息

  1. print(es.cat.fielddata())
  2. print(es.cat.fielddata(format='json', bytes='b'))
  3. #bytes显示字节值的单位,有效选项为:'b','k','kb','m','mb','g','gb','t','tb' ,'p','pb'
  4. #formatAccept标头的简短版本,例如json,yaml

es.cat.health,从集群中health里面过滤出简洁的集群健康信息

  1. print(es.cat.health())
  2. print(es.cat.health(format='json'))

es.cat.help,返回es.cat的帮助信息

  1. print(es.cat.help())

es.cat.indices,返回索引的信息

  1. print(es.cat.indices())
  2. print(es.cat.indices(index='py3'))
  3. print(es.cat.indices(index='py3', format='json'))

es.cat.master,返回集群中主节点的IP,绑定IP和节点名称

  1. print(es.cat.master())
  2. print(es.cat.master(format='json'))

es.cat.nodeattrs,返回节点的自定义属性

  1. print(es.cat.nodeattrs())
  2. print(es.cat.nodeattrs(format='json'))

es.cat.nodes,返回节点的拓扑,这些信息在查看整个集群时通常很有用,特别是大型集群。我有多少符合条件的节点

  1. print(es.cat.nodes())
  2. print(es.cat.nodes(format='json'))

es.cat.plugins,返回节点的插件信息

  1. print(es.cat.plugins())
  2. print(es.cat.plugins(format='json'))

es.cat.segments,返回每个索引的Lucene有关的信息

  1. print(es.cat.segments())
  2. print(es.cat.segments(index='py3'))
  3. print(es.cat.segments(index='py3', format='json'))

es.cat.shards,返回哪个节点包含哪些分片的信息

  1. print(es.cat.shards())
  2. print(es.cat.shards(index='py3'))
  3. print(es.cat.shards(index='py3', format='json'))

es.cat.thread_pool,获取有关线程池的信息

  1. print(es.cat.thread_pool())

6.7 Snapshot 快照相关

  1. # es.snapshot.create,在存储库中创建快照。
  2. repository 存储库名称。
  3. snapshot快照名称。
  4. body快照定义。
  5. # es.snapshot.delete,从存储库中删除快照。
  6. # es.snapshot.create_repository。注册共享文件系统存储库。
  7. # es.snapshot.delete_repository,删除共享文件系统存储库。
  8. # es.snapshot.get,检索有关快照的信息。
  9. # es.snapshot.get_repository,返回有关已注册存储库的信息。
  10. # es.snapshot.restore,恢复快照。
  11. # es.snapshot.status,返回有关所有当前运行快照的信息。通过指定存储库名称,可以将结果限制为特定存储库。
  12. # es.snapshot.verify_repository,返回成功验证存储库的节点列表,如果验证过程失败,则返回错误消息

6.8 Task 任务相关

  1. # es.tasks.get,检索特定任务的信息。
  2. # es.tasks.cancel,取消任务。
  3. # es.tasks.list,任务列表

七. python使用ES搜索小例子

7.1 settings.py中指定连接数据库

  1. DATABASES = {
  2. 'default': {
  3. 'ENGINE': 'django.db.backends.mysql',
  4. 'NAME': 'test_es',
  5. 'HOST': '127.0.0.1',
  6. 'PORT': 3306,
  7. 'USER': 'root',
  8. 'PASSWORD': 'root'
  9. }
  10. }

7.2 models.py中建立模型表,并同步至数据库

  1. from django.db import models
  2. class Car(models.Model):
  3. title = models.CharField(max_length=255)
  4. summary = models.CharField(max_length=255)
  5. img_url = models.CharField(max_length=255, null=True)
  6. tags = models.CharField(max_length=255)
  7. a_url = models.CharField(max_length=255)

​ 随后执行数据库迁移命令

  1. python manage.py makemigrations
  2. python manage.py migrate

7.3 新建一个spider.py文件,配置django环境,爬取数据

  1. #!/usr/bin/env python
  2. import os
  3. if __name__ == "__main__":
  4. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "review_django.settings")
  5. import django
  6. django.setup()
  7. import requests
  8. from bs4 import BeautifulSoup
  9. from concurrent.futures import ThreadPoolExecutor
  10. from app01 import models
  11. def work(k):
  12. response = requests.get(url='https://www.autohome.com.cn/all/{}/#liststart'.format(k))
  13. response.encoding = 'GBK'
  14. soup_obj = BeautifulSoup(response.text, 'html.parser')
  15. div_obj = soup_obj.find(name='div', attrs={"id": "auto-channel-lazyload-article"})
  16. li_list = div_obj.find_all(name='li')
  17. for i in li_list:
  18. no_obj = i.find(name='h3')
  19. if not no_obj: continue
  20. title = i.find(name='h3').text
  21. summary = i.find(name='p').text
  22. a = 'https:' + i.find(name='a').get('href')
  23. img = 'https:' + i.find(name='img').get('src')
  24. tags = a.split('/', 4)[3]
  25. print(response.url, title, tags)
  26. print(summary, img)
  27. models.Car.objects.create(
  28. title=title,
  29. summary=summary,
  30. tags=tags,
  31. img_url=img,
  32. a_url=a
  33. )
  34. def spider():
  35. t = ThreadPoolExecutor(10)
  36. for k in range(1, 60):
  37. t.submit(work, k)
  38. t.shutdown()
  39. spider()

7.4 urls.py中配置路由

  1. from django.conf.urls import url
  2. from app01 import views
  3. urlpatterns = [
  4. # 用于简单显示一个页面,同时展示用户搜索的内容
  5. url(r'index', views.index),
  6. # 将数据库数据写入es
  7. url(r'es', views.es2)
  8. ]

7.5 views.py中视图函数

  1. from django.shortcuts import render, HttpResponse
  2. from django.http import JsonResponse
  3. from elasticsearch import Elasticsearch
  4. from elasticsearch import helpers
  5. from app01 import models
  6. # 实例化一个ES对象
  7. es = Elasticsearch()
  8. # Create your views here.
  9. def filter(search_msg):
  10. body = {
  11. "size": 100, # 返回一百条数据
  12. "query": {
  13. "match": {
  14. "title": search_msg # 从标题中查找输入的关键字
  15. }
  16. },
  17. "highlight": { # 内容高亮显示,使用pre_tags与post_tags定义标签,默认是em标签
  18. "pre_tags": "<b style='color:red;font-size:24px'>",
  19. "post_tags": "</b>",
  20. "fields": {
  21. "title": {} # 将标题高亮显示
  22. }
  23. },
  24. }
  25. # 存储es搜索的结果
  26. res = es.search(index='s18', body=body)
  27. # print(res)
  28. return res
  29. def index(request):
  30. if request.method == "POST":
  31. search_msg = request.POST.get('search_msg')
  32. res = filter(search_msg)
  33. # 将es搜索的结果返回
  34. return JsonResponse(res)
  35. return render(request, 'search.html', locals())
  36. def es2(request):
  37. body = {
  38. "mappings": {
  39. "doc": {
  40. "properties": {
  41. "title": {
  42. "type": "text"
  43. },
  44. "summary": {
  45. "type": "text"
  46. },
  47. "a_url": {
  48. "type": "keyword"
  49. },
  50. "img_url": {
  51. "type": "keyword"
  52. },
  53. "tags": {
  54. "type": "text"
  55. }
  56. }
  57. }
  58. }
  59. }
  60. # es.indices.create(index='s18', body=body)
  61. # print(es.indices.get_mapping())
  62. query_list = models.Car.objects.all()
  63. # 定义写入es的数据格式,使用生成器,减轻内存压力
  64. action = ({
  65. "_index": "s18", # 索引,相当于指定数据库,不存在则创建
  66. "_type": "doc", # 类型,相当于指定表,不存在则创建
  67. "_source": { # 指定要写入的内容
  68. "title": i.title,
  69. "summary": i.summary,
  70. "a_url": i.a_url,
  71. "img_url": i.img_url,
  72. "tags": i.tags
  73. }
  74. }
  75. for i in query_list
  76. )
  77. # helpers会使用java虚拟机帮我们进行该任务
  78. helpers.bulk(es, action)
  79. return HttpResponse('ok es')

7.6 templates文件下写的search.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
  7. <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
  8. <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
  9. </head>
  10. <body>
  11. <nav class="navbar navbar-default">
  12. <div class="container-fluid">
  13. <!-- Brand and toggle get grouped for better mobile display -->
  14. <div class="navbar-header">
  15. <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
  16. <span class="sr-only">Toggle navigation</span>
  17. <span class="icon-bar"></span>
  18. <span class="icon-bar"></span>
  19. <span class="icon-bar"></span>
  20. </button>
  21. <a class="navbar-brand" href="#">Brand</a>
  22. </div>
  23. <!-- Collect the nav links, forms, and other content for toggling -->
  24. <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
  25. <ul class="nav navbar-nav">
  26. <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
  27. <li><a href="#">Link</a></li>
  28. <li class="dropdown">
  29. <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
  30. <ul class="dropdown-menu">
  31. <li><a href="#">Action</a></li>
  32. <li><a href="#">Another action</a></li>
  33. <li><a href="#">Something else here</a></li>
  34. <li role="separator" class="divider"></li>
  35. <li><a href="#">Separated link</a></li>
  36. <li role="separator" class="divider"></li>
  37. <li><a href="#">One more separated link</a></li>
  38. </ul>
  39. </li>
  40. </ul>
  41. {# 搜索框 #}
  42. <form class="navbar-form navbar-left">
  43. <div class="form-group">
  44. <input type="text" class="form-control" placeholder="Search" oninput="foo()" id="search">
  45. </div>
  46. <button type="submit" class="btn btn-default">Submit</button>
  47. <span id="totalNum"></span>
  48. </form>
  49. <ul class="nav navbar-nav navbar-right">
  50. <li><a href="#">Link</a></li>
  51. <li class="dropdown">
  52. <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
  53. <ul class="dropdown-menu">
  54. <li><a href="#">Action</a></li>
  55. <li><a href="#">Another action</a></li>
  56. <li><a href="#">Something else here</a></li>
  57. <li role="separator" class="divider"></li>
  58. <li><a href="#">Separated link</a></li>
  59. </ul>
  60. </li>
  61. </ul>
  62. </div><!-- /.navbar-collapse -->
  63. </div><!-- /.container-fluid -->
  64. <div class="container">
  65. <div class="row">
  66. <div class="col-md-8 col-lg-offset-2">
  67. <div id="showData"></div>
  68. </div>
  69. </div>
  70. </div>
  71. </nav>
  72. </body>
  73. <script>
  74. //搜索
  75. function foo() {
  76. var searchMsg = $('#search').val();
  77. console.log(searchMsg);
  78. $.ajax({
  79. url:"/app01/index",
  80. type: "post",
  81. data: {'search_msg': searchMsg},
  82. success:function (data) {
  83. console.log(data);
  84. if (data){
  85. //展示结果条数
  86. $("#totalNum").html("结果约<b style='color:red'>" + data.hits.total + "<b>")
  87. //结果展示
  88. var html = '';
  89. $.each(data.hits.hits, function (index, item) {
  90. //console.log(item._source.title)
  91. html += "<a href='+ item.a_url +'>\n" +
  92. " <div class=\"article-pic\"></div>\n" +
  93. " <h3>"+item.highlight.title+"</h3>\n" +
  94. " <div class=\"article-bar\">\n" +
  95. " <span class=\"fn-left\"></span>\n" +
  96. " <span class=\"fn-right\">\n" +
  97. " <em><i class=\"icon12 icon12-eye\"></i></em>\n" +
  98. " <em data-class=\"icon12 icon12-infor\" data-articleid=\"945066\"><i class=\"icon12 icon12-infor\"></i>13</em>\n" +
  99. " </span>\n" +
  100. " </div>\n" +
  101. " <p>"+item._source.summary+"</p>\n" +
  102. " </a>";
  103. $("#showData").html(html)
  104. })
  105. }
  106. }
  107. })
  108. }
  109. </script>
  110. </html>

7.7 启动项目先访问es路由,后面访问index即可

elasticsearch基础及在Python中的简单使用的更多相关文章

  1. python基础系列教程——Python中的编码问题,中文乱码问题

    python基础系列教程——Python中的编码问题,中文乱码问题 如果不声明编码,则中文会报错,即使是注释也会报错. # -*- coding: UTF-8 -*- 或者 #coding=utf-8 ...

  2. python中一个简单的webserver

     python中一个简单的webserver 2013-02-24 15:37:49 分类: Python/Ruby 支持多线程的webserver   1 2 3 4 5 6 7 8 9 10 11 ...

  3. Python 中lambda 简单介绍

    转自:https://www.cnblogs.com/AlwaysWIN/p/6202320.html 在学习python的过程中,lambda的语法经常出现,现在将它整理一下,以备日后查看. 1.l ...

  4. 『无为则无心』Python基础 — 8、Python中的数据类型(数值、布尔、字符串)

    目录 1.数据类型介绍 2.数值型(Number) 3.布尔型(bool) 4.None(空值) 5.常量 6.字符串(String) 1.数据类型介绍 (1)什么是数据类型 在生活中,我们日常使用的 ...

  5. 『无为则无心』Python基础 — 11、Python中的数据类型转换

    目录 1.为什么要进行数据类型转换 2.数据类型转换本质 3.数据类型转换用到的函数 4.常用数据类型转换的函数 (1)int()函数 (2)float()函数 (3)str()函数 (4)bool( ...

  6. 『无为则无心』Python基础 — 41、Python中文件的读写操作(一)

    目录 1.文件操作步骤 2.文件的读写操作 (1)文件的打开 (2)打开文件模式 (3)获取一个文件对象 (4)关于文件路径 1.文件操作步骤 当我们要读取或者写入文件时,我们需要打开文件,在操作完毕 ...

  7. 『无为则无心』Python基础 — 61、Python中的迭代器

    目录 1.迭代的概念 2.迭代器的概念 3.可迭代的对象(Iterable) 4.迭代器对象(Iterator) 5.迭代器的使用体验 (1)基本用法 (2)实际应用 1.迭代的概念 (1)什么是迭代 ...

  8. 正则表达式在python中的简单使用

    正则表达式独立与编程语言,基本上所有的编程语言都实现了正则表达式的相关操作.在Python中正则表达式的表现为re模块: import re 其操作有三个方法: my_string = "h ...

  9. Python中实现简单的插件框架

    在系统设计中,经常我们希望设计一套插件机制,在不修改程序主体情况下,动态去加载附能. 我设想的插件系统: 1.通过类来实现 2.自动查找和导入 我们假设需要实现一个简单的插件系统,插件可以接收一个参数 ...

随机推荐

  1. Catch That Cow (BFS)

    题目: Farmer John has been informed of the location of a fugitive cow and wants to catch her immediate ...

  2. 生死状:苹果VS他的供应商

    据知情人士透露,苹果已经组建了代号为Titan的汽车团队,并招募了数百名员工,准备进入汽车领域,iCar大有呼之欲出之势.事实上,苹果CEO蒂姆-库克早在去年就参观了宝马位于莱比锡的核心工厂,学习如何 ...

  3. curator配置及使用

    1.action.yml --- actions: 1: action: index_settings options: index_settings: index: routing.allocati ...

  4. 烧钱时代终结!O2O还能玩啥花样?

    最终的最终,饱受亏损.烧钱玩补贴等争议的美团还是追随滴滴/快的.赶集/58的步伐,与大众点评愉快的在一起了!美团和大众点评作为O2O行业的领军企业,都因为不堪忍受持续地投入却不见回报的模式而不得不放低 ...

  5. Introduction Of Gradient Descent

    不是一个机器学习算法 是一种基于搜索的优化方法 作用:最小化一个损失函数 梯度上升法:最大化一个效用函数 import matplotlib.pyplot as plt import numpy as ...

  6. 百度地图API:使用百度定位

    准备工作: 1.申请百度地图API 2.下载百度地图的SDK 3.将SDK包中的BaiduLBS_Android.jar文件放到,项目里的app/libs里面 4.在src/main目录下创建一个名为 ...

  7. MVC04

    1. 从页面到action 讲述controller与View之间的具体运作关系 在上次添加的名为Movie的Model内添加 下面我们尝试为该model内的属性添加attribute 具体修改如下: ...

  8. bp(net core)+easyui+efcore实现仓储管理系统——入库管理之三存储过程(三十九)

    abp(net core)+easyui+efcore实现仓储管理系统目录 abp(net core)+easyui+efcore实现仓储管理系统——ABP总体介绍(一) abp(net core)+ ...

  9. JAVA基础之IO流知识总结

    一.IO流体系图 IO常用的几个流: [I/O流原理作用] Input/Output:输入输出机制 输入机制:允许java程序获取外部设备的数据(磁盘,光盘,网络等). 输出机制:保留java程序中的 ...

  10. python 深浅拷贝 元组 字典 集合操作

    深浅拷贝 :值拷贝 :ls = [,,] res = ls 则print(res)就是[,,] 浅拷贝 :ls.copy() 深拷贝:ls3 = deepcopy(ls) # 新开辟列表空间,ls列表 ...