python对接elasticsearch的基本操作,,基本操作#!/usr


基本操作

#!/usr/bin/env python# -*- coding: utf-8 -*-# author tomfrom elasticsearch import Elasticsearchfrom pprint import pprint# 连接es,直接传一个ip字符串参数也可以,他会帮你封装成列表的es_host = ‘47.106.79.197‘es = Elasticsearch([es_host],                   # 在做任何操作之前,先进行嗅探                   # sniff_on_start=True,                   # 节点没有响应时,进行刷新,重新连接                   # sniff_on_connection_fail=True,                   # # 每 60 秒刷新一次                   # sniffer_timeout=60                   )###########################关于基本信息的查看############# #测试是否能连通# pprint(es.ping())# #查看集群的健康信息# pprint(es.cluster.health())# #查看当前集群的节点信息# pprint(es.cluster.client.info())# #查看集群的更多信息# pprint(es.cluster.state())# 使用cat查看更多信息# pprint(es.cat.health())# pprint(es.cat.master())# pprint(es.cat.nodes())# pprint(es.cat.count())###########################关于索引的操作############### 查看当前集群的所有的索引# pprint(es.cat.indices())# 创建索引# 创建索引的时候可以指定body参数,就是mapping的type的配置信息# mapping={}# res=es.indices.create(index=‘my-index‘,ignore=True,body=mapping)# pprint(res)# pprint(es.cat.indices())# 删除索引# res=es.indices.delete(index=‘my-index‘)# pprint(res)# 判断索引是否存在# res=es.indices.exists(index=‘my-index‘)# pprint(res)#########################关于单条数据的操作##################### 插入数据的时候指定的索引可以不存在,但是不建议这么做,最好先判断,不存在集创建,这样不易出问题# 添加一条数据# 使用index新增可以不指定id,会随机生成一个id,# 如果指定了id,当id存在的时候,就会对这条数据进行更新,id不存在则新建# 这边要注意一下,使用index更新,他会用新的字典,直接替换原来的整个字典,与update方法是不一样的# body = {‘name‘: ‘xiaosan‘, ‘age‘: 18, ‘sex‘: ‘girl‘, }# res = es.index(index=‘my-index‘, body=body, id=‘OokS028BE9BB6NkUgJnI‘)# pprint(res)#使用create新增一条数据# 注意使用create新增数据必须制定id,create本质也是调用了index# body = {‘name‘: ‘xiaosan‘, ‘age‘: 18, ‘sex‘: ‘girl‘, }# res=es.create(index=‘my-index‘,body=body,id=1)# 查询一条数据(通过id来查询)# res=es.get(index=‘my-index‘,id=‘OYkK028BE9BB6NkUOZll‘)# pprint(res)# 查询所有数据# body = {‘query‘: {‘match_all‘: {}}}# res = es.search(index=‘my-index‘, body=body)# pprint(res)# 删除数据(通过指定索引和id进行删除)# res=es.delete(index=‘my-index‘,id=‘O4kZ028BE9BB6NkUUpm4‘)# pprint(res)# 更新数据(指定id更新数据,在es7之后要更新的数据需要用一个大字典包裹着,并且,key为doc )# body={‘doc‘:{‘heigh‘:180}}   #这个更新操作是在原来的基础上增加一个字段,而如果字段原来存在就会进行替换# res=es.update(index=‘my-index‘,id=‘OokS028BE9BB6NkUgJnI‘,body=body)#########################关于多条数据或者高级操作############################# 使用term或者terms进行精确查询body = {    "query":{        "term":{            "name":"python"        }    }}######### 查询name="python"的所有数据es.search(index="my-index",doc_type="test_type",body=body)body = {    "query":{        "terms":{            "name":[                "python","android"            ]        }    }}# 搜索出name="python"或name="android"的所有数据res=es.search(index="my_index",doc_type="test_type",body=body)print(res)########### match与multi_match# match:匹配name包含python关键字的数据body = {    "query":{        "match":{            "name":"python"        }    }}# 查询name包含python关键字的数据es.search(index="my_index",doc_type="test_type",body=body)body = {    "query":{        "multi_match":{            "query":"深圳",            "fields":["name","addr"]        }    }}# 查询name和addr包含"深圳"关键字的数据es.search(index="my_index",doc_type="test_type",body=body)############ idsbody = {    "query":{        "ids":{            "type":"test_type",            "values":[                "1","2"            ]        }    }}# 搜索出id为1或2d的所有数据es.search(index="my_index",doc_type="test_type",body=body)########### 复合查询bool#bool有3类查询关系,must(都满足),should(其中一个满足),must_not(都不满足)body = {    "query":{        "bool":{            "must":[                {                    "term":{                        "name":"python"                    }                },                {                    "term":{                        "age":18                    }                }            ]        }    }}# 获取name="python"并且age=18的所有数据es.search(index="my_index",doc_type="test_type",body=body)#############  切片式查询body = {    "query":{        "match_all":{}    },    "from":2,    # 从第二条数据开始    "size":4    # 获取4条数据}# 从第2条数据开始,获取4条数据es.search(index="my_index",doc_type="test_type",body=body)###########范围查询body = {    "query":{        "range":{            "age":{                "gte":18,       # >=18                "lte":30        # <=30            }        }    }}# 查询18<=age<=30的所有数据es.search(index="my_index",doc_type="test_type",body=body)#########前缀查询body = {    "query":{        "prefix":{            "name":"p"        }    }}# 查询前缀为"赵"的所有数据es.search(index="my_index",doc_type="test_type",body=body)######  通配符查询body = {    "query":{        "wildcard":{            "name":"*id"        }    }}# 查询name以id为后缀的所有数据es.search(index="my_index",doc_type="test_type",body=body)######## 排序body = {    "query":{        "match_all":{}    },    "sort":{        "age":{                 # 根据age字段升序排序            "order":"asc"       # asc升序,desc降序        }    }}##########  filter_path# 只需要获取_id数据,多个条件用逗号隔开es.search(index="my_index",doc_type="test_type",filter_path=["hits.hits._id"])#########   获取所有数据es.search(index="my_index",doc_type="test_type",filter_path=["hits.hits._*"])#########  count#执行查询并获取该查询的匹配数########  获取数据量es.count(index="my_index",doc_type="test_type")#度量类聚合#获取最小值body = {    "query":{        "match_all":{}    },    "aggs":{                        # 聚合查询        "min_age":{                 # 最小值的key            "min":{                 # 最小                "field":"age"       # 查询"age"的最小值            }        }    }}# 搜索所有数据,并获取age最小的值es.search(index="my_index",doc_type="test_type",body=body)body = {    "query":{        "match_all":{}    },    "aggs":{                        # 聚合查询        "max_age":{                 # 最大值的key            "max":{                 # 最大                "field":"age"       # 查询"age"的最大值            }        }    }}####### 搜索所有数据,并获取age最大的值es.search(index="my_index",doc_type="test_type",body=body)body = {    "query":{        "match_all":{}    },    "aggs":{                        # 聚合查询        "sum_age":{                 # 和的key            "sum":{                 # 和                "field":"age"       # 获取所有age的和            }        }    }}# 搜索所有数据,并获取所有age的和es.search(index="my_index",doc_type="test_type",body=body)#获取平均值body = {    "query":{        "match_all":{}    },    "aggs":{                        # 聚合查询        "avg_age":{                 # 平均值的key            "sum":{                 # 平均值                "field":"age"       # 获取所有age的平均值            }        }    }}# 搜索所有数据,获取所有age的平均值es.search(index="my_index",doc_type="test_type",body=body)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author tom
from elasticsearch import Elasticsearch
from pprint import pprint

# 连接es,直接传一个ip字符串参数也可以,他会帮你封装成列表的
es_host = ‘47.106.79.197‘
es = Elasticsearch([es_host],
# 在做任何操作之前,先进行嗅探
# sniff_on_start=True,
# 节点没有响应时,进行刷新,重新连接
# sniff_on_connection_fail=True,
# # 每 60 秒刷新一次
# sniffer_timeout=60
)

###########################关于基本信息的查看############
# #测试是否能连通
# pprint(es.ping())
# #查看集群的健康信息
# pprint(es.cluster.health())
# #查看当前集群的节点信息
# pprint(es.cluster.client.info())
# #查看集群的更多信息
# pprint(es.cluster.state())
# 使用cat查看更多信息
# pprint(es.cat.health())
# pprint(es.cat.master())
# pprint(es.cat.nodes())
# pprint(es.cat.count())


###########################关于索引的操作##############
# 查看当前集群的所有的索引
# pprint(es.cat.indices())
# 创建索引
# 创建索引的时候可以指定body参数,就是mapping的type的配置信息
# mapping={}
# res=es.indices.create(index=‘my-index‘,ignore=True,body=mapping)
# pprint(res)
# pprint(es.cat.indices())

# 删除索引
# res=es.indices.delete(index=‘my-index‘)
# pprint(res)

# 判断索引是否存在
# res=es.indices.exists(index=‘my-index‘)
# pprint(res)


#########################关于单条数据的操作####################
# 插入数据的时候指定的索引可以不存在,但是不建议这么做,最好先判断,不存在集创建,这样不易出问题

# 添加一条数据
# 使用index新增可以不指定id,会随机生成一个id,
# 如果指定了id,当id存在的时候,就会对这条数据进行更新,id不存在则新建
# 这边要注意一下,使用index更新,他会用新的字典,直接替换原来的整个字典,与update方法是不一样的
# body = {‘name‘: ‘xiaosan‘, ‘age‘: 18, ‘sex‘: ‘girl‘, }
# res = es.index(index=‘my-index‘, body=body, id=‘OokS028BE9BB6NkUgJnI‘)
# pprint(res)

#使用create新增一条数据
# 注意使用create新增数据必须制定id,create本质也是调用了index
# body = {‘name‘: ‘xiaosan‘, ‘age‘: 18, ‘sex‘: ‘girl‘, }
# res=es.create(index=‘my-index‘,body=body,id=1)


# 查询一条数据(通过id来查询)
# res=es.get(index=‘my-index‘,id=‘OYkK028BE9BB6NkUOZll‘)
# pprint(res)

# 查询所有数据
# body = {‘query‘: {‘match_all‘: {}}}
# res = es.search(index=‘my-index‘, body=body)
# pprint(res)

# 删除数据(通过指定索引和id进行删除)
# res=es.delete(index=‘my-index‘,id=‘O4kZ028BE9BB6NkUUpm4‘)
# pprint(res)

# 更新数据(指定id更新数据,在es7之后要更新的数据需要用一个大字典包裹着,并且,key为doc )
# body={‘doc‘:{‘heigh‘:180}} #这个更新操作是在原来的基础上增加一个字段,而如果字段原来存在就会进行替换
# res=es.update(index=‘my-index‘,id=‘OokS028BE9BB6NkUgJnI‘,body=body)


#########################关于多条数据或者高级操作####################
######### 使用term或者terms进行精确查询
body = {
"query":{
"term":{
"name":"python"
}
}
}
######### 查询name="python"的所有数据
es.search(index="my-index",doc_type="test_type",body=body)
body = {
"query":{
"terms":{
"name":[
"python","android"
]
}
}
}
# 搜索出name="python"或name="android"的所有数据
res=es.search(index="my_index",doc_type="test_type",body=body)
print(res)


########### match与multi_match
# match:匹配name包含python关键字的数据
body = {
"query":{
"match":{
"name":"python"
}
}
}
# 查询name包含python关键字的数据
es.search(index="my_index",doc_type="test_type",body=body)

body = {
"query":{
"multi_match":{
"query":"深圳",
"fields":["name","addr"]
}
}
}
# 查询name和addr包含"深圳"关键字的数据
es.search(index="my_index",doc_type="test_type",body=body)

############ ids

body = {
"query":{
"ids":{
"type":"test_type",
"values":[
"1","2"
]
}
}
}
# 搜索出id为1或2d的所有数据
es.search(index="my_index",doc_type="test_type",body=body)

########### 复合查询bool
#bool有3类查询关系,must(都满足),should(其中一个满足),must_not(都不满足)

body = {
"query":{
"bool":{
"must":[
{
"term":{
"name":"python"
}
},
{
"term":{
"age":18
}
}
]
}
}
}
# 获取name="python"并且age=18的所有数据
es.search(index="my_index",doc_type="test_type",body=body)

############# 切片式查询
body = {
"query":{
"match_all":{}
},
"from":2, # 从第二条数据开始
"size":4 # 获取4条数据
}
# 从第2条数据开始,获取4条数据
es.search(index="my_index",doc_type="test_type",body=body)

###########范围查询

body = {
"query":{
"range":{
"age":{
"gte":18, # >=18
"lte":30 # <=30
}
}
}
}
# 查询18<=age<=30的所有数据
es.search(index="my_index",doc_type="test_type",body=body)

#########前缀查询
body = {
"query":{
"prefix":{
"name":"p"
}
}
}
# 查询前缀为"赵"的所有数据
es.search(index="my_index",doc_type="test_type",body=body)


###### 通配符查询
body = {
"query":{
"wildcard":{
"name":"*id"
}
}
}
# 查询name以id为后缀的所有数据
es.search(index="my_index",doc_type="test_type",body=body)


######## 排序
body = {
"query":{
"match_all":{}
},
"sort":{
"age":{ # 根据age字段升序排序
"order":"asc" # asc升序,desc降序
}
}
}


########## filter_path
# 只需要获取_id数据,多个条件用逗号隔开
es.search(index="my_index",doc_type="test_type",filter_path=["hits.hits._id"])

######### 获取所有数据
es.search(index="my_index",doc_type="test_type",filter_path=["hits.hits._*"])

######### count
#执行查询并获取该查询的匹配数

######## 获取数据量
es.count(index="my_index",doc_type="test_type")

#度量类聚合
#获取最小值

body = {
"query":{
"match_all":{}
},
"aggs":{ # 聚合查询
"min_age":{ # 最小值的key
"min":{ # 最小
"field":"age" # 查询"age"的最小值
}
}
}
}
# 搜索所有数据,并获取age最小的值
es.search(index="my_index",doc_type="test_type",body=body)



body = {
"query":{
"match_all":{}
},
"aggs":{ # 聚合查询
"max_age":{ # 最大值的key
"max":{ # 最大
"field":"age" # 查询"age"的最大值
}
}
}
}

####### 搜索所有数据,并获取age最大的值
es.search(index="my_index",doc_type="test_type",body=body)


body = {
"query":{
"match_all":{}
},
"aggs":{ # 聚合查询
"sum_age":{ # 和的key
"sum":{ # 和
"field":"age" # 获取所有age的和
}
}
}
}
# 搜索所有数据,并获取所有age的和
es.search(index="my_index",doc_type="test_type",body=body)



#获取平均值
body = {
"query":{
"match_all":{}
},
"aggs":{ # 聚合查询
"avg_age":{ # 平均值的key
"sum":{ # 平均值
"field":"age" # 获取所有age的平均值
}
}
}
}
# 搜索所有数据,获取所有age的平均值
es.search(index="my_index",doc_type="test_type",body=body)

python对接elasticsearch的基本操作

评论关闭