python對接elasticsearch的基本操作


一.關於集群的基本操作

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

# 連接es,直接傳一個ip字符串參數也可以,他會幫你封裝成列表的
es_host = 'XXX.XX.XX.XXX'
#es = Elasticsearch(es_host,)
#es=Elasticsearch(['192.168.10.10', '192.168.10.11', '192.168.10.12'])   #連接集群
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,如果id已經存在就會報錯(ConflictError重復錯誤,所以少用)
# 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')   #刪除指定id
# pprint(res)
# print(es.delete_by_query(index='p2', body={"query": {"match": {"age": 20}}}))  #刪除符合條件



# 更新數據(指定id更新數據,在es7之后要更新的數據需要用一個大字典包裹着,並且,key為doc )
# body={'doc':{'heigh':180}}   #這個更新操作是在原來的基礎上增加一個字段,而如果字段原來存在就會進行替換
# res=es.update(index='my-index',id='OokS028BE9BB6NkUgJnI',body=body)


#判斷指定id的數據是否存在

pprint(es.exists(index='person1', id='xVywInIBMTX0DMkCECea'))

 

 

四.關於多條數據或者高級操作


######### 使用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._*"])

#度量類聚合
#獲取最小值

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)

 

五.對返回的字段進行過濾

   filter_path參數用於過濾減少es返回信息,可以指定返回相關的內容,還支持一些通配符的操作*

# 主要是對_source同一級的字段進行過濾
print(es.search(index="p1", body=body, filter_path=["hits.hits"]))
print(es.search(index="p1", body=body, filter_path=["hits.hits._source"]))
print(es.search(index="p1", body=body, filter_path=["hits.hits._source", "hits.total"]))
print(es.search(index="p1", body=body, filter_path=["hits.*"]))
print(es.search(index="p1", body=body, filter_path=["hits.hits._*"]))

 

六.獲取數據量

#########  count
#執行查詢並獲取該查詢的匹配數

########  獲取數據量
es.count(index="my_index",doc_type="test_type")

pprint(es.count(index='person'))
pprint(es.count(index='person')['count'])

   結果:

{'_shards': {'failed': 0, 'skipped': 0, 'successful': 1, 'total': 1},
 'count': 1}
1

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM