研究了下ES,写了一个python版的关于ES的增删改查代码:

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

# 增 改
# title已存在则修改,不存在则添加
def update_es(title, body):
    result = es.search(index='myindex', q='title:{}'.format(title), from_='0', size=5)['hits']['hits']
    exist = bool(result)
    if exist:
        _id = result[0]['_id']
        es.update(index='myindex',doc_type='mytype',id=_id,body=body)
    else:
        es.index(index='myindex',doc_type='mytype',body=body)


# 删除匹配到title为key的值
def delete_es(key):
    es.delete_by_query(index='myindex',doc_type="mytype",body={"query":{"match":{'title':key}}})

# 查找关键字为key的,并指定返回的数目
def search_es(key,start=1,end=10):
    body = {
        "query": {
            "bool": {
                # should 或关系, must 与关系
                "should": [
                    {
                        # match 匹配、含有; term 相等、等价
                        "match": {
                            "title": key
                        }
                    },
                    {
                        "match": {
                            "actor": key
                        }
                    },
                    {
                        "match": {
                            "director": key
                        }
                    }
                ]
            }
        }
    }

    response = es.search(index="myindex", body=body)
    index = 1
    result = []

    for hit in response['hits']['hits']:
        source = hit['_source']
        if index>=start and index<=end:
            result.append(source)
        index += 1

    return result






感觉跟mongo还是很像的,以后再继续深入。

  • 查阅资料所知:暂时没有像mongo那样有个client.close()函数来释放链接,但是可以放进thread里进行连接,然后关掉thread线程。