通过Python库elasticsearch_dsl处理elasticsearch

了解elasticsearch_dsl

ElasticSearch与数据库的对应关系

ES RDBS
index database
type table
filed column

通过Python库elasticsearch_dsl处理ES

添加连接

1
2
from elasticsearch_dsl import connections
connections.create_connection(hosts=['10.0.4.122:9200'], timeout=20)

获取index(database)

1
2
3
4
5
6
7
8
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search

client = Elasticsearch('10.0.4.122:9200')

indexs = client.indices.get('*') # 获取所有的index

indexnames = indexs.keys()

获取type(table)

1
2
index = indexnames[0]
tables = indexs[index]['mappings'].keys

获取所有的字段(columns)

1
2
table = tables[0]
colunms = inidexs[table]['properties'].keys()

数据查询

1
2
3
4
5
6
7
8
9
10
11
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search

client = Elasticsearch('10.0.4.122:9200')
s = Search().using(client).query("match", account_number=5)
response = s.execute()

result = []
for row in response.hits:
# print row.to_dict()
result.append(row.to_dict())