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')

以上就是全部知识点内容,感谢大家的阅读和对我们的支持。

(0)

相关推荐

  • Python 操作 ElasticSearch的完整代码

    官方文档:https://elasticsearch-py.readthedocs.io/en/master/ 1.介绍 python提供了操作ElasticSearch 接口,因此要用python来操作ElasticSearch,首先要安装python的ElasticSearch包,用命令pip install elasticsearch安装或下载安装:https://pypi.python.org/pypi/elasticsearch/5.4.0 2.创建索引 假如创建索引名称为ott,类型

  • python Elasticsearch索引建立和数据的上传详解

    今天我想讲一讲关于Elasticsearch的索引建立,当然提前是你已经安装部署好Elasticsearch. ok,先来介绍一下Elaticsearch,它是一款基于lucene的实时分布式搜索和分析引擎,是后台系统,用来存储数据,检索数据,属于完全命令行交互. 那为什么选择python作为脚本进行命令的写入和数据的上传呢?那是因为Python里面有固定的模板,可以上传数据到Elasticsearch. 接下来就聊一聊该如何编写代码: 我们上传数据之后,数据到哪里去了呢? 存在索引里面了. 那

  • elasticsearch python 查询的两种方法

    elasticsearch python 查询的两种方法,具体内容如下所述: from elasticsearch import Elasticsearch es = Elasticsearch res1 = es.search(index="2018-07-31", body={"query": {"match_all": {}}}) print(es1) {'_shards': {'failed': 0, 'skipped': 0, 'suc

  • Python对ElasticSearch获取数据及操作

    使用Python对ElasticSearch获取数据及操作,供大家参考,具体内容如下 Version Python :2.7 ElasticSearch:6.3 代码: #!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2018/7/4 @Author : LiuXueWen @Site : @File : ElasticSearchOperation.py @Software: PyCharm @Descri

  • python elasticsearch从创建索引到写入数据的全过程

    python elasticsearch从创建索引到写入数据 创建索引 from elasticsearch import Elasticsearch es = Elasticsearch('192.168.1.1:9200') mappings = { "mappings": { "type_doc_test": { #type_doc_test为doc_type "properties": { "id": { "

  • 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 原因:当前用户没有执行权限 解

  • JAVA环境搭建之MyEclipse10+jdk1.8+tomcat8环境搭建详解

    一.安装JDK 1.下载得到jdk-8u11-windows-i586.1406279697.exe,直接双击运行安装,一直next就可以,默认是安装到系统盘下面Program Files, 我这里装在D:\Program Files\Java下面,注意安装完jdk之后会自动运行安装jre,这时的安装路径最好和jdk一样,方便管理,我的都是在D:\Program Files\Java下面. 2.环境变量配置: 右击"我的电脑",点击"属性":选择"高级系统

  • Java MyBatis框架环境搭建详解

    目录 一.MyBatis简介 1.MyBatis历史 2.MyBatis特性 3.MyBatis下载 4.和其它持久化层技术对比 JDBC Hibernate 和 JPA MyBatis 二.搭建MyBatis 1.开发环境 2.创建maven工程 3.创建MyBatis的核心配置文件 4.创建mapper接口 5.创建MyBatis的映射文件 6.通过junit测试功能 7.加入log4j日志功能 一.MyBatis简介 1.MyBatis历史 MyBatis最初是Apache的一个开源项目i

  • Vite开发环境搭建详解

    目录 Vite初始化项目 集成Vue-Router 集成Vuex 集成Git提交验证 集成Eslint 配置alias ​Vite​​​现在可谓是炙手可热,可能很多小伙伴还没有使用过​​Vite​​​,但是我相信大多数小伙伴已经在使用​​Vite​​​了,因为是太香了有没有.可能在使用过程中很多东西​​Vite​​​不是配置好的,并不像​​Vue-cli​​配置的很周全,那么今天就说一下如何配置开发环境,其中主要涉及到的点有一下几个: TypeScript Vuex Vue-Router E2E

  • React入门教程之Hello World以及环境搭建详解

    前言 React 是一个用于构建用户界面的 JavaScript 库.react主要用于构建UI,很多人认为 React 是 MVC 中的 V(视图).关注React也已经很久了,一直没能系统地深入学习,最近准备好好研究一下,并且亲自动手做一些实践. 不管是学习一门语言也好,还是学习一个框架也好,都是从最初的hello world程序开始的,今天我们也来用react写一个hello world出来,了解一下如何编写及运行React. 入门教程及环境搭建 在官方文档中,有一种方式是基于npm的,我

  • 基于Vue2的移动端开发环境搭建详解

    前言 vue2.0发布了,那么还在用vue1.x的你,是不是也有所心动呢?下面这篇文章就给大家详细介绍基于Vue2的移动端开发环境搭建的详细步骤,下面来一起看看吧. 一.vue-cli 首先还是介绍我们的脚手架工具,因为它能让我们省去大部分的配置时间,这里只给出简单步骤,保证你的命令顺利运行的前提是安装最新版本的 node 和 npm,这里不赘述升级流程 全局安装 vue-cli npm install vue-cli -g 借此也全局安装一个 webpack npm install webpa

  • android开发环境搭建详解(eclipse + android sdk)

    本开发环境为:eclipse + android sdk,步骤说明的顺序,没有特别要求,看个人爱好了 步骤说明: 1.安装eclipse 2.配置jdk 3.安装android sdk 4.安装ADT,关联eclipse和android 详细说明: 1.安装eclipse * 到官方网下载eclipse(http://www.eclipse.org/downloads/),我是下载的Eclipse IDE for Java EE Developers. * 正常解压安装,注意记得路径就可以了 2

  • 如何在python开发工具PyCharm中搭建QtPy环境(教程详解)

    在Python的开发工具PyCharm中安装QtPy5(版本5):打开"File"--"Settings"--"Project Interpreter",点击窗口中右侧点添加按钮,然后在弹出的窗口添加PyQt5模块包,单击Install Package按钮,如图所示: 安装好安装PyQt5后,需要用同样的方法安装pyqt5-tools,安装PyQt5后没有designer.exe就是因为没有安装pyqt5-tools.安装好PyQt5后,desi

  • 详解python开发环境搭建

    虽然网上有很多python开发环境搭建的文章,不过重复造轮子还是要的,记录一下过程,方便自己以后配置,也方便正在学习中的同事配置他们的环境. 1.准备好安装包 1)上python官网下载python运行环境(http://www.jb51.net/softs/416037.html),目前比较稳定的是python-3.5.2 2)上pycharm官网下载最新版的IDE(http://www.jb51.net/softs/299378.html),官网提供了mac.windows和linux三种版

  • Windows系统中搭建Go语言开发环境图文详解

    目录 1.Go语言简介 2.安装Git 3.Go 工具链(编译器)安装 3.1.环境变量GOROOT 3.2.环境变量GOPATH 3.3.Go常用命令 4.包管理 4.1.go module 4.2.gopm 5.编写Go语言代码的IDE或编辑工具 5.1.基于VSCode的Go开发环境 5.1.1.安装VSCode 5.1.2.安装插件 5.1.3.常用配置 5.2.GoLand 5.3.Vim 5.4.其他Go代码编写工具 6.Go语言学习资料分享 本文详细讲述如何在 Windows 系统

随机推荐