【ElasticSearch】学习快速入门笔记(1)——用python进行创建,插入,查找操作

所给环境:

已经搭建好的elasticSearch集群,给出了连接端口和连接ip。

先看下有哪些集群,以免index相同,误删(或者自动更新)了别人的文件。
1.获得所有index
rest方式:

curl 'xxx.xxx.xxx.xxx:9200/_cat/indices?v'

在这里插入图片描述
2.获得所有type

curl -XGET 'http://xx.xxx.xxx.xxx:9200/_mapping?pretty=true'

在这里插入图片描述

用python建立链接:

from elasticsearch import Elasticsearch
es = Elasticsearch([{'host':'xxx.xxx.xxx.xxx','port':9200}])

自己建立一个index以备查询,这里的index相当于database,但是不完全一样,它像一个链接……而不是存了一堆表的数据库。确定索引前,需要确定存储位置。
参考网址:https://elasticsearch-py.readthedocs.io/en/master/

from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch([{'host':'xxx.xxx.xxx.xxx','port':9200}])

doc = {
    'author': 'kimchy',
    'text': 'Hello world!',
    'timestamp': datetime.now(),
}
res = es.index(index="test-index", doc_type='tweet', id=1, body=doc)
print(res['result'])

# 从test-index的索引读取tweet类型的数据,数据id为1,
# 取出来的数据保存在字典的'_source'字段里
res = es.get(index="test-index", doc_type='tweet', id=1)
print(res['_source'])

# refresh后写入磁盘,没有refresh,1s内存到内存,暂时不可搜索的。
es.indices.refresh(index="test-index")

# match_all得到索引中的所有文档
res = es.search(index="test-index", body={"query": {"match_all": {}}})
print("Got %d Hits:" % res['hits']['total']['value'])
for hit in res['hits']['hits']:
    print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])

这样就完成了简单的建立和查询功能。

删除索引:
curl -X DELETE ‘localhost:9200/test’

发布了140 篇原创文章 · 获赞 114 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/qinglingLS/article/details/97272859
今日推荐