Python访问Elasticsearch最直接的方法就是用requests库

easy_install requests  
或者
yum install python-requests  

搜索功能:

def search(uri, term):  
    """Simple Elasticsearch Query"""
    query = json.dumps({
        "query": {
            "match": {
                "description": term
            }
        }
    })
    response = requests.get(uri, data=query)
    results = json.loads(response.text)
    return results

格式化结果:

def format_results(results):  
    """Print results nicely:
    doc_id) content
    """
    data = [doc for doc in results['hits']['hits']]
    for doc in data:
        print("%s) %s" % (doc['_id'], doc['_source']['description']))

建立索引

def create_doc(uri, doc_data={}):  
    """Create new document."""
    query = json.dumps(doc_data)
    response = requests.post(uri, data=query)
    print(response)

完整的python程序:

import requests  
import json

def search(uri, term):  
    """Simple Elasticsearch Query"""
    query = json.dumps({
        "query": {
            "match": {
                "description": term
            }
        }
    })
    response = requests.get(uri, data=query)
    results = json.loads(response.text)
    return results

def format_results(results):  
    """Print results nicely:
    doc_id) content
    """
    data = [doc for doc in results['hits']['hits']]
    for doc in data:
        print("%s) %s" % (doc['_id'], doc['_source']['description']))

def create_doc(uri, doc_data={}):  
    """Create new document."""
    query = json.dumps(doc_data)
    response = requests.post(uri, data=query)
    print(response)


if __name__ == '__main__':  
    uri_search = 'http://localhost:9200/products/_search'
    uri_create = 'http://localhost:9200/movies/movie/'

    results = search(uri_search, "Whi")
    format_results(results)

    #create_doc(uri_create, {"title":"The Godfather","director":"Francis Ford Coppola","year": 1972})
comments powered by Disqus