ES(Elasticsearch)常用操作与Python客户端

2.3k 词

ES常用操作

之前老板本的ES使用的创建索引的指令已经失效了。


curl -X PUT 'http://127.0.0.1:9200/testcase/' -d '
        index:
            number_of_shards:3
            number_of_replicas:2
'

索性就不创建索引,直接插入数据, ES不用像关系型数据库那样,需要在插插入数据前,先定义数据库表结构,没有create table的过程。

curl -X POST http://127.0.0.1:9200/testcase/case/1 -d  '{"phone":"15811111111" ,"identity":"xxx", "credit":"xxx"}'

输出结果:

{“_index”:“testcase”,“_type”:“case”,“_id”:“1”,“_version”:4,“_shards”:{“total”:2,“successful”:1,“failed”:0},“created”:false}

读出的方式没有变化:

curl -X GET http://localhost:9200/testcase/case/1

输出结果:
{“_index”:“testcase”,“_type”:“case”,“_id”:“1”,“_version”:2,“found”:true,“_source”:{“phone”:“15811111111” ,“identity”:“xxx”, “credit”:“xxx”}}

ES的Python操作库:

from elasticsearch import Elasticsearch

#与ES建立连接
es = Elasticsearch('127.0.0.1:9200')

#创建索引
es.indices.create(index='testcase', ignore=400)


#向索引中插入一条数据
es.index(index="testcase", doc_type="test-type", id=1, body={"phone":"15812345678" ,"identity":"789", "credit":"efg"})


#取得一条数据,按ID号
es.get(index="testcase", doc_type="test-type", id=1)
['source']

#刷新数据
es.indices.refresh(index="testcase")

#按条件检索记录
res = es.search(index='testcase')

res = es.search( index='testcase', doctype='test-type', body={ 'query': { 'match': { 'credit': 'abc' } }})

#检索所有数据
res = es.search(index="testcase", body={"query":{"match_all":{}}}) 

#按条件检索
res = es.search( index='testcase', body={ 'query': { 'match': { 'phone': '10086' } }})

#统计记录个数
res['hits']['total']

另外,通过PYES库,也可以操作数据。

from pyes.connection import connect
from pyes import *
from pyes.query import *
from pyes.es import ResultSet
from pyes.connection import connect
c = connect(servers=['127.0.0.1:9200'])

myFilter = TermFilter('phone', '123')

q = FilteredQuery(MatchAllQuery(), myFilter).search()
mymodel = lambda x,y:y