1. 程式人生 > >【python Elasticsearch】python 簡單操作Elasticsearch

【python Elasticsearch】python 簡單操作Elasticsearch

python提供了操作ElasticSearch 介面,因此要用python來操作ElasticSearch,首先要安裝python的ElasticSearch包

pip install elasticsearch

官網提供的python操作ES的簡單例子是:

# -*- coding:utf-8 -*-

from datetime import datetime

from elasticsearch import Elasticsearch


es = Elasticsearch()
# 建立索引
es.indices.create(index='my-index', ignore=400)

es.index(index="my-index", doc_type="test-type", id=42, body={"any": "data", "timestamp": datetime.now()})

# 檢視資料
kk=es.get(index="my-index", doc_type="test-type", id=42)['_source']


# 列印資料
print(kk)

列印內容:

{'any': 'data', 'timestamp': '2018-11-16T11:51:52.820416'}

Process finished with exit code 0

在瀏覽器介面我們看到了剛剛建立的索引和資料

在這裡插入圖片描述

例子2:

# -*- coding:utf-8 -*-

from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch()


# 內容
doc = {
    'author': 'kimchy',
    'text': 'Elasticsearch: cool. bonsai cool.',
    'timestamp': datetime.now(),
}

# 建立索引
res = es.index(index="test-index", doc_type='tweet', id=1, body=doc)


# 通過索引獲取資料
res = es.get(index="test-index", doc_type='tweet', id=1)
print(res['_source'])

es.indices.refresh(index="test-index")

# 搜尋
res = es.search(index="test-index", body={"query": {"match_all": {}}})
print("Got %d Hits:" % res['hits']['total'])
for hit in res['hits']['hits']:
    print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])

執行結果:

{'author': 'kimchy', 'timestamp': '2018-11-16T12:09:08.729595', 'text': 'Elasticsearch: cool. bonsai cool.'}
Got 1 Hits:
2018-11-16T12:09:08.729595 kimchy: Elasticsearch: cool. bonsai cool.

Process finished with exit code 0

在這裡插入圖片描述

# -*- coding:utf-8 -*-

from elasticsearch import Elasticsearch

es = Elasticsearch()
# # 建立一個名為 news 的索引
# result = es.indices.create(index='news', ignore=400)
# print(result)

# 刪除索引
# result = es.indices.delete(index='news', ignore=[400, 404])
# print(result)

# # 插入資料
#
# data = {'title': '美國留給伊拉克的是個爛攤子嗎', 'url': 'http://view.news.qq.com/zt2011/usa_iraq/index.htm'}
#
# # 需要指定id
# result = es.create(index='news', doc_type='politics', id=1, body=data)
# print(result)

# 不需要指定id,系統自動建立
# es.index(index='news', doc_type='politics', body=data)


# # 跟新資料
#
# data = {
#     'title': '美國留給伊拉克的是個爛攤子嗎',
#     'url': 'http://view.news.qq.com/zt2011/usa_iraq/index.htm',
#     'date': '2011-12-16'
# }
# result = es.update(index='news', doc_type='politics', body=data, id=1)
# print(result)
#
# # 另外更新操作其實利用 index() 方法同樣可以做到
# # es.index(index='news', doc_type='politics', body=data, id=1)
#
# # 可以看到,index() 方法可以代替我們完成兩個操作,如果資料不存在,那就執行插入操作,如果已經存在,那就執行更新操作,非常方便。
#
#
# # 刪除資料
#
# result = es.delete(index='news', doc_type='politics', id=1)
# print(result)


# 插入資料
datas = [
    {
        'title': '美國留給伊拉克的是個爛攤子嗎',
        'url': 'http://view.news.qq.com/zt2011/usa_iraq/index.htm',
        'date': '2011-12-16'
    },
    {
        'title': '公安部:各地校車將享最高路權',
        'url': 'http://www.chinanews.com/gn/2011/12-16/3536077.shtml',
        'date': '2011-12-16'
    },
    {
        'title': '中韓漁警衝突調查:韓警平均每天扣1艘中國漁船',
        'url': 'https://news.qq.com/a/20111216/001044.htm',
        'date': '2011-12-17'
    },
    {
        'title': '中國駐洛杉磯領事館遭亞裔男子槍擊 嫌犯已自首',
        'url': 'http://news.ifeng.com/world/detail_2011_12/16/11372558_0.shtml',
        'date': '2011-12-18'
    }
]

for data in datas:
    es.index(index='news2', doc_type='politics', body=data)


# 這裡我們指定了四條資料,都帶有 title、url、date 欄位,然後通過 index() 方法將其插入 Elasticsearch 中,索引名稱為 news,型別為 politics。

# 查詢資料
result = es.search(index='news2', doc_type='politics')
print(result)

在這裡插入圖片描述