# 连接es
es = Elasticsearch(["127.0.0.1"], http_auth=('es_service', ''), port=9200)
# 插入数据,index,doc_type名称可以自定义,id可以根据需求赋值,body为内容 如果不指定 id,会自动生成一个 id
def index(database, table, id, doc):
# return es.index(index=database, doc_type=table, id=id, body=doc)
return es.index(index=database, doc_type=table, body=doc)
# 插入数据, 必须指定id
def create(database, table, id, body):
return es.create(index=database, doc_type=table, id=id, body=body)
# 删除
def deleted(database, table, id):
return es.delete(index=database, doc_type=table, id=id)
# 删除index
def deleted_index(database):
return es.indices.delete(index=database, ignore=[400, 404])
# 更新
def update(database, table, id, body):
return es.update(index=database, doc_type=table, id=id, body=body)
# 根据id查询
def select_by_id(database, table, id):
return es.get(index=database, doc_type=table, id=id)['_source']
# 条件查询
def search(database, table, query):
return es.search(index=database, doc_type=table, body=query)['hits']['hits']
# 条件删除
def delete_by_query(database, table, query):
return es.delete_by_query(index=database, doc_type=table, body=query)
def batch_add(actions):
printhelpers.bulk(client=es, actions=actions)
if __name__ == '__main__':
body = {'id': 1, 'lv_id': 12, 'sentiment': 0, 'news_id': 1673590, 'review': '123',
'keyword': '受不了 错字连篇', 'ner': '', 'test_id': 'X3eRQnoBptFMHoC6cLwP'}
database = 'test_index'
table = 'type'
id = body['test_id']
batch_data_list = [body]
resp = index(database, 'type', id, body)
print('es操作result', resp)
resp = deleted(index, 'review_feature', doc['news_id'])
levels = ['info', 'debug', 'warn', 'error']
action = [{
"_index": database,
"_type": table,
"_source": {
"title": i
}
} for i in range(100)]
resp = batch_add(action)
resp = create(database, 'type', id, body)
resp = deleted_index(database )
update_body = {"doc": body}
resp = update(database, 'type', id, update_body)
resp = select_by_id(database, table, id)
query = {'query': {'range': {'age': {'lt': 11}}}}
query = {'query': {'term': {'review': '123'}}} # 精确 条件查询
query = {'query': {'match': {'review': '123'}}} # 模糊 条件查询
resp = delete_by_query(database, table, query)
resp = search(database, table, query)
print(es.info())
print('es操作result', resp)
python3 操作es简单学习
最新推荐文章于 2024-04-19 02:15:24 发布