python elasticsearch环境搭建详解
作者:古月月月胡 发布时间:2021-03-31 03:50:42
标签:python,elasticsearch
windows下载zip
linux下载tar
下载地址:https://www.elastic.co/downloads/elasticsearch
解压后运行:bin/elasticsearch (or bin\elasticsearch.bat on Windows)
检查是否成功:访问 http://localhost:9200
linux下不能以root用户运行,
普通用户运行报错:
java.nio.file.AccessDeniedException
原因:当前用户没有执行权限
解决方法: chown linux用户名 elasticsearch安装目录 -R
例如:chown ealsticsearch /data/wwwroot/elasticsearch-6.2.4 -R
PS:其他Java软件报.AccessDeniedException错误也可以同样方式解决,给 执行用户相应的目录权限即可
2|0代码实例
如下的代码实现类似链家网小区搜索功能。
从文件读取小区及地址信息写入es,然后通过小区所在城市code及搜索关键字 匹配到对应小区。
代码主要包含三部分内容:
1.创建索引
2.用bulk将批量数据存储到es
3.数据搜索
注意:
代码的es版本交低2.xx版本,高版本在创建的索引数据类型有所不同
#coding:utf8
from __future__ import unicode_literals
import os
import time
import config
from datetime import datetime
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk
class ElasticSearch():
def __init__(self, index_name,index_type,ip ="127.0.0.1"):
'''
:param index_name: 索引名称
:param index_type: 索引类型
'''
self.index_name =index_name
self.index_type = index_type
# 无用户名密码状态
#self.es = Elasticsearch([ip])
#用户名密码状态
self.es = Elasticsearch([ip],http_auth=('elastic', 'password'),port=9200)
def create_index(self,index_name="ftech360",index_type="community"):
'''
创建索引,创建索引名称为ott,类型为ott_type的索引
:param ex: Elasticsearch对象
:return:
'''
#创建映射
_index_mappings = {
"mappings": {
self.index_type: {
"properties": {
"city_code": {
"type": "string",
# "index": "not_analyzed"
},
"name": {
"type": "string",
# "index": "not_analyzed"
},
"address": {
"type": "string",
# "index": "not_analyzed"
}
}
}
}
}
if self.es.indices.exists(index=self.index_name) is True:
self.es.indices.delete(index=self.index_name)
res = self.es.indices.create(index=self.index_name, body=_index_mappings)
print res
def build_data_dict(self):
name_dict = {}
with open(os.path.join(config.datamining_dir,'data_output','house_community.dat')) as f:
for line in f:
line_list = line.decode('utf-8').split('\t')
community_code = line_list[6]
name = line_list[7]
city_code = line_list[0]
name_dict[community_code] = (name,city_code)
address_dict = {}
with open(os.path.join(config.datamining_dir,'data_output','house_community_detail.dat')) as f:
for line in f:
line_list = line.decode('utf-8').split('\t')
community_code = line_list[6]
address = line_list[10]
address_dict[community_code] = address
return name_dict,address_dict
def bulk_index_data(self,name_dict,address_dict):
'''
用bulk将批量数据存储到es
:return:
'''
list_data = []
for community_code, data in name_dict.items():
tmp = {}
tmp['code'] = community_code
tmp['name'] = data[0]
tmp['city_code'] = data[1]
if community_code in address_dict:
tmp['address'] = address_dict[community_code]
else:
tmp['address'] = ''
list_data.append(tmp)
ACTIONS = []
for line in list_data:
action = {
"_index": self.index_name,
"_type": self.index_type,
"_id": line['code'], #_id 小区code
"_source": {
"city_code": line['city_code'],
"name": line['name'],
"address": line['address']
}
}
ACTIONS.append(action)
# 批量处理
success, _ = bulk(self.es, ACTIONS, index=self.index_name, raise_on_error=True)
#单条写入 单条写入速度很慢
#self.es.index(index=self.index_name,doc_type="doc_type_test",body = action)
print('Performed %d actions' % success)
def delete_index_data(self,id):
'''
删除索引中的一条
:param id:
:return:
'''
res = self.es.delete(index=self.index_name, doc_type=self.index_type, id=id)
print res
def get_data_id(self,id):
res = self.es.get(index=self.index_name, doc_type=self.index_type,id=id)
# # 输出查询到的结果
print res['_source']['city_code'], res['_id'], res['_source']['name'], res['_source']['address']
def get_data_by_body(self, name, city_code):
# doc = {'query': {'match_all': {}}}
doc = {
"query": {
"bool":{
"filter":{
"term":{
"city_code": city_code
}
},
"must":{
"multi_match": {
"query": name,
"type":"phrase_prefix",
"fields": ['name^3', 'address'],
"slop":1,
}
}
}
}
}
_searched = self.es.search(index=self.index_name, doc_type=self.index_type, body=doc)
data = _searched['hits']['hits']
return data
if __name__=='__main__':
#数据插入es
obj = ElasticSearch("ftech360","community")
obj.create_index()
name_dict, address_dict = obj.build_data_dict()
obj.bulk_index_data(name_dict,address_dict)
#从es读取数据
obj2 = ElasticSearch("ftech360","community")
obj2.get_data_by_body(u'保利','510100')
来源:https://www.cnblogs.com/i-love-python/p/11443978.html
0
投稿
猜你喜欢
- (1) 我们先用arange函数创建一个数组并改变其维度,使之变成一个三维数组:>>> a = np.arange(24)
- 本篇不是教给大家如何去学习python,有需要详细深入学习的朋友可以参阅:Python基础语言学习笔记总结(精华)本文通过一周快速学习pyt
- 这篇文章主要介绍了python return逻辑判断表达式实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价
- 按位与或(&、|、^):按照二进制进行逻辑运算例如:数字换成二进制,各自位上的0/1进行逻辑运算,得到的结果转换为数字3 &
- 突然发现自己对Web前端技术掌握得很少很少,就是自己最感兴趣的XHTML+CSS部分知道也不算多。在XHTML 1.1规定的诸多元素中,我平
- 本文实例为大家分享了PyQt5实现简单计算器的具体代码,供大家参考,具体内容如下下面我们将介绍使用python的PyQt5图形界面来编写一个
- 一、 功能Android端或者Android终端的远程截图至本地电脑中二、使用说明1.adb截图工具可用于Android手机及Android
- 最近一段时间都在学django,现在的网站基本都要使用到富文本编辑器,今天就记录下使用django的管理后台的一个富文本编辑器的第三方库 D
- 本文实例讲述了Python包,__init__.py功能与用法。分享给大家供大家参考,具体如下:包:为了组织好模块,将多个模块组合为一个包,
- 本文实例讲述了Python实现查询某个目录下修改时间最新的文件。分享给大家供大家参考,具体如下:通过Python脚本,查询出某个目录下修改时
- requests安装和使用下载安装:pip install requests#requests模块import requests#发送请求
- 所谓的列表推导式,就是指的轻量级循环创建列表。基本使用方式# 创建一个0-10的列表a = [x for x in range(11)]pr
- 前面讲解了使用纯numpy实现数值微分和误差反向传播法的手写数字识别,这两种网络都是使用全连接层的结构。全连接层存在什么问题呢?那就是数据的
- 该程序通过绘制树干(最初是树;后来是树枝)并递归地添加树来绘制“树”。 使用Pillow。利用递归函数绘制分形树(fractal tree)
- 开发环境安装最新版Python下载地址:https://www.python.org/downloads/运行Python1.交互方式运行用
- 比如代码 binfo = {'name':'jay','age':20,'pytho
- 在Python中,生成器和函数很像,都是在运行的过程中才会去确定各种变量的值,所以在很多情况下,会导致各种各样的问题。def generat
- 分割成一个包含两个元素列表的列对于一个已知分隔符的简单分割(例如,用破折号分割或用空格分割).str.split() 方法就足够了 。 它在
- 昨天晚上才发现已经出了jQuery的1.3版本,于是下载下来,把原来一个兄弟翻译的1.2.6的文档移植到了1.3中,点击这里可
- 基于底层数据来开发不难,无非是将用户输入变量作为筛选条件,将参数映射到 sql 语句,并生成一个 sql 语句然后再去数据库执行最后再利用