Python ElasticSearch基礎教程
阿新 • • 發佈:2019-01-11
- ElasticSearch簡介
ElasticSearch是一個基於Lucene的搜尋伺服器。它提供了一個分散式多使用者能力的全文搜尋引擎,基於RESTful web介面。Elasticsearch是用Java開發的,並作為Apache許可條款下的開放原始碼釋出,是當前流行的企業級搜尋引擎。設計用於雲端計算中,能夠達到實時搜尋,穩定,可靠,快速,安裝使用方便。
我們建立一個網站或應用程式,並要新增搜尋功能,但是想要完成搜尋工作的建立是非常困難的。我們希望搜尋解決方案要執行速度快,我們希望能有一個零配置和一個完全免費的搜尋模式,我們希望能夠簡單地使用JSON通過HTTP來索引資料,我們希望我們的搜尋伺服器始終可用,我們希望能夠從一臺開始並擴充套件到數百臺,我們要實時搜尋,我們要簡單的多租戶,我們希望建立一個雲的解決方案。因此我們利用Elasticsearch來解決所有這些問題及可能出現的更多其它問題。
官網連結:
2.Elasticsearch方法的使用及原始碼
1.Elasticsearch模組的安裝與引用:
Python環境中,第一步需要安裝相對應的elasticsearch模組,pip install elasticsearch,
然後在檔案中引用from elasticsearch import Elasticsearch
2.Elasticsearch的連線
obj = ElasticSearchClass("59.110.41.175", "9200", "", "")
其中ElasticSearchClass裡面是elasticsearch的的一些常用方法:
3. ElasticSearch的原始碼:
class ElasticSearchClass(object):
def __init__(self, host, port, user, passwrod):
self.host = host
self.port = port
self.user = user
self.password = passwrod
self.connect()
def connect(self):
“””客戶端的連線”””
self.es = Elasticsearch(hosts=[{'host' : self.host, 'port': self.port}],
http_auth=(self.user, self.password ))
def insertDocument(self, index, type, body, id=None):
'''
插入一條資料body到指定的index、指定的type下;可指定Id,若不指定,ES會自動生成
:param index: 待插入的index值
:param type: 待插入的type值
:param body: 待插入的資料 -> dict型
:param id: 自定義Id值
:return:
'''
return self.es.index(index=index, doc_type=type, body=body, id=id)
def count(self, indexname):
"""
:param indexname:
:return: 統計index總數
"""
return self.conn.count(index=indexname)
def delete(self, indexname, doc_type, id):
"""
:param indexname:
:param doc_type:
:param id:
:return: 刪除index中具體的一條
"""
self.es.delete(index=indexname, doc_type=doc_type, id=id)
def get(self, doc_type, indexname, id):
return self.es.get(index=indexname,doc_type=doc_type, id=id)
def searchindex(self, index):
"""
查詢所有index資料
"""
try:
return self.es.search(index=index)
except Exception as err:
print(err)
def searchDoc(self, index=None, type=None, body=None):
'''
查詢index下所有符合條件的資料
:param index:
:param type:
:param body: 篩選語句,符合DSL語法格式
:return:
'''
return self.es.search(index=index, doc_type=type, body=body)
def search(self,index,type,body,size=10,scroll='10s'):
"""
根據index,type查詢資料,
其中size預設為十條資料,可以修改為其他數字,但是不能大於10000
"""
return self.es.search(index=index, doc_type=type,body=body,size=size,scroll=scroll)
def scroll(self, scroll_id, scroll):
"""
根據上一個查詢方法,查詢出來剩下所有相關資料
"""
return self.es.scroll(scroll_id=scroll_id, scroll=scroll)
3.Elasticsearch的基本操作
1.elasticsearch的連線
obj = ElasticSearchClass("59.110.41.00", "9200", "", "")
連線elasticsearch客戶端
2.資料的的插入
obj.insertDocument(index=”question”,type='text,id=9,body={"any":body,"timestamp":datetime.now()})
其中index和type是固定傳入,id可以自己傳入也可以系統生成,其中body資料為自己組合的資料
3.資料的刪除
dd = obj.delete(index='question', type='text', id=7310)
資料刪除時候是根據id進行刪除,刪除資料時候,index,type需要和之前傳入時候的index,type保持一致
4. 資料的搜尋
其中,搜尋之後資料顯示預設為十條資料
4.1、通過index搜尋資料
res = obj.search(indexname=index)
4.2、通過body搜尋資料
4.2.1、全部匹配:
# 查詢所有資料
body = {
"query":{
"match_all":{}
}
}
response = obj.search(index="question",type="text",body=body)
返回的資料預設顯示為十條資料,其中hits[“total”]為查詢數量總數
其中Match_all 預設匹配所有的資料
4.2.2、廣泛匹配某個欄位
body = {
"query" : {
"match" : {
"data.content" : "一根鐵絲"
}
}
}
Match預設匹配某個欄位
response = obj.search(index="question",type="text",body=body)
返回結果:
4.2.3、匹配多個欄位
body = {
"query": {
"bool": {
"should": [
{ "match": { "data.content": "一根鐵絲" }},
{ "match": { "data.question_content": "一根鐵絲" }},
{ "match": { "data.ask_content.content": '一根鐵絲' }}
],
}
}
}
Should或匹配可以匹配某個欄位也可以匹配所有欄位,其中至少有一個語句要匹配,與 OR 等價
response = obj.search(index="question",type="text",body=body,scroll='5s')
4.2.4、匹配所有欄位
body = {
"query": {
"bool": {
"must": [
{ "match": { "data.content": "李阿姨" }},
{ "match": { "data.question_content": "李阿姨" }},
{ "match": { "data.ask_content.content": '李阿姨' }}
],
}
}
}
Must必須匹配所有需要查詢的欄位
response = obj.search(index="question",type="text",body=body,scroll='5s')
返回結果
4.2.5、短語匹配查詢:
精確匹配一系列單詞或者短語
body = {
"query" : {
"match_phrase" : {
"data.content" : "一根鐵絲"
}
}
}
response = obj.search(index="question",type="text",body=body,scroll='5s')
返回結果:
4.2.6、高亮搜尋:
許多應用都傾向於在每個搜尋結果中 高亮 部分文字片段,以便讓使用者知道為何該文件符合查詢條件。在 Elasticsearch 中檢索出高亮片段也很容易。
再次執行前面的查詢,並增加一個新的 highlight 引數:
Body = {
"query" : {
"match_phrase" : {
"about" : "rock climbing"
}
},
"highlight": {
"fields" : {
"about" : {}
}
}
}
當執行該查詢時,返回結果與之前一樣,與此同時結果中還多了一個叫做 highlight 的部分。這個部分包含了 about 屬性匹配的文字片段,並以 HTML 標籤 <em></em> 封裝:
{
...
"hits": {
"total": 1,
"max_score": 0.23013961,
"hits": [
{
...
"_score": 0.23013961,
"_source": {
"data.content": "李阿姨"
},
"highlight": {
"about": [
"張阿姨和<em>李阿姨</em>"
]
}
}
]
}
}
4.資料的返回格式
{
...
"hits": {
"total": 1,
"max_score": 0.23013961,
"hits": [
{
...
"_score": 0.23013961,
"_source": {
"欄位名1": "XXX",
"欄位名2": "XXX",
"欄位名3": "XXX",
}
}
]
}
}