小雨点点789 发表于 2017-5-5 07:36:15

一段 Python 连接 elasticsearch 的代码

  安装

pip install elasticsearch
  es_client.py

# -*- coding: utf-8 -*-
import random
import requests
from elasticsearch import Transport
from elasticsearch.connection import RequestsHttpConnection
from config.base_config import ES_HOSTS, ES_INDEX, ES_CONNECTION_NUM
hosts = []
for host in ES_HOSTS:
hosts.append({'url': host})
connection_pool = Transport(hosts, connection_class=RequestsHttpConnection).connection_pool
def get_es_conn():
return connection_pool.get_connection()
def search(query):
con = get_es_conn()
status, headers, data = con.perform_request('GET', '/'+ES_INDEX+'/_search?q='+query)
return data

  调用

import json
from es_client import search
query_str = "((title:*"+keyword+"*)OR(key_words:*"+keyword+"*))AND(is_public:true)AND(publish_time:)"
query_str += "&size=" + str(page_size)
query_str += "&from=" + str((page - 1) * page_size)      
res = json.loads(search(query_str))
页: [1]
查看完整版本: 一段 Python 连接 elasticsearch 的代码