好久没有写代码了,最近想做一个基于spring boot + vue + elasticsearch + NLP(语义相关性)的小系统练练手,系统后面可以成为一个聊天机器人,客服系统的原型等等。

所以今天就带来第一篇文章:elasticsearch的hello world入门

一、安装es

目标:在本地安装一个单节点es玩

1.下载es

目前官网最新的下载地址是:https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.2.0-linux-x86_64.tar.gz

下载之后,解压到一个目录,比如你的开发目录:your_path/elasticsearch

2.更改配置文件

a. 配置文件路径:config/elasticsearch.yml

b. 把下面的项改为成自己的值

# Use a descriptive name for your cluster:
# 集群名
cluster.name: my-ces
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
# 节点名
node.name: ces-node-1
# Path to directory where to store the data (separate multiple locations by comma):
# es存储数据的地方
path.data: ~/es/data
#
# Path to log files:
# es的运行log
path.logs: ~/es/logs
# Set the bind address to a specific IP (IPv4 or IPv6):
# 绑定地址为本地
network.host: _local_
#
# Set a custom port for HTTP:
# 监听短裤
http.port: 9200

3. 运行测试

a. 运行bin/elasticsearch,

b. 打开浏览器输入:localhost:9200,如果显示以下内容,则成功。

{
"name" : "ces-node-1",//设置的节点名
"cluster_name" : "my-ces",//配置的集群名
"cluster_uuid" : "6XOfx0eQReG3iMKek9hdTA",
"version" : {
"number" : "7.2.0",
"build_flavor" : "default",
"build_type" : "tar",
"build_hash" : "508c38a",
"build_date" : "2019-06-20T15:54:18.811730Z",
"build_snapshot" : false,
"lucene_version" : "8.0.0",
"minimum_wire_compatibility_version" : "6.8.0",
"minimum_index_compatibility_version" : "6.0.0-beta1"
},
"tagline" : "You Know, for Search"
}

4. 安装ik插件并测试

ik是什么

ik是一个分词插件,要使用es来检索中文数据,需要安装本插件。

安装

按照https://github.com/medcl/elasticsearch-analysis-ik上面但指引安装并测试就可以了

二、创建索引

首先索引类似一个mysql数据库的table,你要往es里面存数据,当然就需要es里面先建立一个索引。

网上很多教程就是基于原生的http接口教大家如何创建索引,如果对于es或者http不熟悉的朋友,经常搞得一头雾水,今天我教大家使用es的python包来做。

安装python的elasticsearch包

pip install elasticsearch

定义mapping.json

这个的作用就是,定义index长什么样子,哪些字段需要被检索,哪些字段不检索,假如现在有一个一问一答的数据:

question: 世界上最高的山峰是什么
answer:当然是珠峰了

我们想使用es来检索,做成一个问答机器人,那么我们定义如下的index结构:

{
"settings":{
"number_of_shards":2, //可以先忽略
"number_of_replicas":1
},
"mappings": {
"dynamic": "strict",
"properties": {
"question": {//需要被索引
"type": "text",
"analyzer": "ik_max_word",//ik分词器
"search_analyzer": "ik_smart",//ik分词器
"index": true,
"boost": 8
},
"answer": {
"type": "text",
"index": false
}
}
}
}

并保存为:es_index_mapping.json

创建索引

使用python版本的es很简单就实现了,直接上代码:

from elasticsearch import Elasticsearch
from elasticsearch import helpers
from common.conf import ServiceConfig
import os.path as path
import json class EsDriver:
def __init__(self):
self.service_conf = ServiceConfig()
# hosts 实际就是: [{"host": "localhost", "port": 9200}]
self.es = Elasticsearch(hosts=self.service_conf.get_es_hosts()) def create_index(self, index_name):
dir_root = path.normpath("%s/.." % path.dirname(path.abspath(__file__)))
with open(dir_root + "/data/es_index_mapping.json", 'r') as json_file:
index_mapping_json = json.load(json_file)
# 调用indices.create,传入index name(你自己取),然后就创建好了
return self.es.indices.create(index_name, body=index_mapping_json)

三、批量导入数据

创建好了index,那么我们就要往里面导入数据,python的es包提供批量导入的功能,只需要几行代码就可以实现:

假如你有一个文件qa.processed.txt,是这样的格式:

query\t['answer1','answer2'],比如

你开心吗\t["很开心"]

class EsDriver:

    ...

    def bulk_insert(self, index_name, bulk_size=500):
doc_list = [] with open('/data/qa.processed.txt', 'r') as qa_file:
for line in qa_file:
ls = line.strip().split('\t')
if len(ls) != 2:
continue doc_list.append({
"_index": index_name, # 要插入到哪个index
"_type": "_doc",
"_source": {
"question": ls[0],# query
"answer": ls[1] # answer
}
})
if len(doc_list) % bulk_size == 0:
# 调用es helper的方法 bulk插入到索引中
helpers.bulk(self.es, doc_list, stats_only=True)
del doc_list[:]
if len(doc_list) != 0:
helpers.bulk(self.es, doc_list) print("bulk insert done")

执行完上述的操作之后,数据就哗哗的导入到es中了。

搜索

导入数据之后,我们就要去搜索数据了,同样的使用es包里面的search函数就搞定了。比如现在你想搜索:你好

那么代码如何写呢?

class EsDriver:

    ...

    def search(self, query, index_name):
return self.es.search(index=index_name, body={
"query": {
"match": {
"question": query
}
}
})

然后你打印一下返回的结果,就知道数据返回是什么样了。

附:几个常见状态操作

  1. 索引状态
  • curl -X GET "localhost:9200/_cat/indices?v&pretty"
  1. 集群状态
  • curl -X GET "localhost:9200/_cat/health?v&pretty"
  1. 索引mapping & setting
  • curl -X GET "localhost:9200/customer?pretty"
  • customer是index
  1. 通过id查询一个index下的文档数据
  • curl -X GET "localhost:9200/customer/_doc/1?pretty"
  • customer是index

后续文章带来:数据集离线处理:构造特征,入es库,java 工程构建

有兴趣的小伙伴,可以添加博主vx交流:crazy042438,一起来做

基于Spring Boot的问答系统之一:elasticsearch 7.2的hello world入门的更多相关文章

  1. 基于Spring Boot、Spring Cloud、Docker的微服务系统架构实践

    由于最近公司业务需要,需要搭建基于Spring Cloud的微服务系统.遍访各大搜索引擎,发现国内资料少之又少,也难怪,国内Dubbo正统治着天下.但是,一个技术总有它的瓶颈,Dubbo也有它捉襟见肘 ...

  2. 基于Spring Boot/Spring Session/Redis的分布式Session共享解决方案

    分布式Web网站一般都会碰到集群session共享问题,之前也做过一些Spring3的项目,当时解决这个问题做过两种方案,一是利用nginx,session交给nginx控制,但是这个需要额外工作较多 ...

  3. step6----->往工程中添加spring boot项目------->修改pom.xml使得我的project是基于spring boot的,而非直接基于spring framework

    文章内容概述: spring项目组其实有多个projects,如spring IO platform用于管理external dependencies的版本,通过定义BOM(bill of mater ...

  4. 基于Spring Boot的图片上传

    package com.clou.inteface.domain.web.user; import java.io.File; import java.io.IOException; import j ...

  5. Https系列之三:让服务器同时支持http、https,基于spring boot

    Https系列会在下面几篇文章中分别作介绍: 一:https的简单介绍及SSL证书的生成二:https的SSL证书在服务器端的部署,基于tomcat,spring boot三:让服务器同时支持http ...

  6. 基于Spring Boot,使用JPA动态调用Sql查询数据

    在<基于Spring Boot,使用JPA操作Sql Server数据库完成CRUD>,<基于Spring Boot,使用JPA调用Sql Server数据库的存储过程并返回记录集合 ...

  7. 基于Spring Boot,使用JPA调用Sql Server数据库的存储过程并返回记录集合

    在上一篇<基于Spring Boot,使用JPA操作Sql Server数据库完成CRUD>中完成了使用JPA对实体数据的CRUD操作. 那么,有些情况,会把一些查询语句写在存储过程中,由 ...

  8. spring boot 2.0 整合 elasticsearch6.5.3,spring boot 2.0 整合 elasticsearch NoNodeAvailableException

    原文地址:spring boot 2.0 整合 elasticsearch NoNodeAvailableException 原文说的有点问题,下面贴出我的配置: 原码云项目地址:https://gi ...

  9. 基于Spring Boot和Shiro的后台管理系统FEBS

    FEBS是一个简单高效的后台权限管理系统.项目基础框架采用全新的Java Web开发框架 —— Spring Boot 2.0.3,消除了繁杂的XML配置,使得二次开发更为简单:数据访问层采用Myba ...

随机推荐

  1. 前台提交数据到node服务器(post方式)

    post方式同样有两种办法,一种是表单提交,一种是ajax提交. 在此之前需要安装一个中间件:body-parser,安装好后在app.js头部引入: bodyParser = require('bo ...

  2. redis 获取自增数

    近期,有一个项目需要用到数字的自增整数,范围是0-199999,但公司数据库是mongodb.同时装有mysql.redis等存储数据的这些数据库,其中redis是集群模式,mongodb是paa(  ...

  3. Hive安装与简单使用并集成SparkSQL

    ## Hive环境搭建1. hive下载:http://archive-primary.cloudera.com/cdh5/cdh/5/hive-1.1.0-cdh5.7.0.tar.gzwget h ...

  4. Python学习笔记整理总结【Django】:Model操作(二)

    1.操作汇总 # 增 # # models.Tb1.objects.create(c1='xx', c2='oo') 增加一条数据,可以接受字典类型数据 **kwargs # obj = models ...

  5. hihttps教你在Wireshark中提取旁路https解密源码

    大家好,我是hihttps,专注SSL web安全研究,今天本文就是教大家怎样从wireshark源码中,提取旁路https解密的源码,非常值得学习和商业应用. 一.旁路https解密条件 众所周知, ...

  6. 11 种在大多数教程中找不到的JavaScript技巧

    当我开始学习JavaScript时,我把我在别人的代码.code challenge网站以及我使用的教程之外的任何地方发现的每一个节省时间的技巧都列了一个清单. 在这篇文章中,我将分享11条我认为特别 ...

  7. Java 学习笔记之 Error和Exception的联系

    Error和Exception的联系: Error和Exception的联系 继承结构:Error和Exception都是继承于Throwable,RuntimeException继承自Excepti ...

  8. Kafka 学习笔记之 High Level Consumer相关参数

    High Level Consumer相关参数 自动管理offset auto.commit.enable = true auto.commit.interval.ms = 60*1000 手动管理o ...

  9. Django学习之model进阶

    一 QuerySet 可切片 使用Python 的切片语法来限制查询集记录的数目 .它等同于SQL 的LIMIT 和OFFSET 子句.   >>> Entry.objects.al ...

  10. JavaScript设计模式——原型模式

    原型模式: 原型模式是指原型实例指向创建对象的种类,并通过拷贝这些原型创建新的对象,是一种用来创建对象的模式,也就是创建一个对象作为另一个对象的prototype属性: prototype警告:学习了 ...