python连接elasticsearch查询数据

python连接elasticsearch获取数据

原文:https://blog.csdn.net/ziqiaowang/article/details/54972279

  1. # -*- encoding: utf-8 -*-

  2. import sys

  3. import json

  4. from elasticsearch import Elasticsearch

  5.  
  6. reload(sys)

  7. sys.setdefaultencoding("utf8")

  8.  
  9. ######################################################

  10. # 用于连接ES环境,查询检索小区信息,返回排名靠前10的小区信息。

  11. # http_auth=('es_username', 'es_passwd')

  12. # es_search(city,name):es_search(深圳,登科花园)

  13. ######################################################

  14.  
  15.  
  16. es = Elasticsearch(

  17. ['xxx.xxx.xxx.xxx'],

  18. http_auth=('elastic', 'passwd'),

  19. port=9200

  20. )

  21.  
  22.  
  23. def es_search(city, name):

  24. query_json = {

  25. "bool": {

  26. "must": {

  27. "term": {

  28. "city": city

  29. }

  30. },

  31. "must_not":{

  32. "term": {

  33. "base_inf.kind":'商铺'

  34. }

  35. },

  36. "should": [

  37. {

  38. "match": {

  39. "message": name

  40. }

  41. }

  42. ]

  43. }

  44. }

  45.  
  46. source_arr = ["name",

  47. "Long_lat.lon",

  48. "Long_lat.lat",

  49. "detail_inf",

  50. "avg_price",

  51. "base_inf.kind",

  52. "base_inf.build_time"]

  53.  
  54.  
  55.  
  56. res = es.search(index="st_soufang", body={"query": query_json, "_source": source_arr}) # 获取所有数据

  57.  
  58. # 获取第一条数据,得分最高。

  59. top_10_recodes = res['hits']['hits']

  60. # print json.dumps(top_10_recodes)

  61. return [top_10_recodes]

  62. #

  63. # for item in best_recode:

  64. # if item != '_source':

  65. # print item,best_recode[item]

  66.  
  67.  
  68. if __name__ == "__main__":

  69. # 测试单例

  70. city = '深圳'

  71. name = '东方星大厦'

  72. es_search(city, name)

猜你喜欢

转载自blog.csdn.net/jacke121/article/details/81137094