搜索引擎Elasticearch

官方网址:https://www.elastic.co/cn/products/elasticsearch

Githubhttps://github.com/elastic/elasticsearch

ElasticaSearch安装

config:配置文件目录

data:索引目录,存放索引文件的地方

logs:日志目录

modules:模块目录,包括了es的功能模块

plugins :插件目录,es支持插件机制

 三个配置文件

ES的配置文件的地址根据安装形式的不同而不同:

使用ziptar安装,配置文件的地址在安装目录的confifig下。

使用RPM安装,配置文件在/etc/elasticsearch下。

使用MSI安装,配置文件的地址在安装目录的confifig下,并且会自动将confifig目录地址写入环境变量 ES_PATH_CONF

本教程使用的zip包安装,配置文件在ES安装目录的confifig下。

配置文件如下:

elasticsearch.yml : 用于配置Elasticsearch运行参数 jvm.options : 用于配置Elasticsearch JVM设置

log4j2.properties: 用于配置Elasticsearch日志

 elasticsearch.yml

配置格式是YAML,可以采用如下两种方式:

方式1:层次方式

path: data: /var/lib/elasticsearch logs: /var/log/elasticsearch

方式2:属性方式

path.data: /var/lib/elasticsearch path.logs: /var/log/elasticsearch

本项目采用方式2,例子如下:

cluster.name: xuecheng

node.name: xc_node_1

network.host: 0.0.0.0

http.port: 9200

transport.tcp.port: 9300

node.master: true

node.data: true

#discovery.zen.ping.unicast.hosts: ["0.0.0.0:9300", "0.0.0.0:9301", "0.0.0.0:9302"]

discovery.zen.minimum_master_nodes: 1

bootstrap.memory_lock: false

node.max_local_storage_nodes: 1

path.data: D:\ElasticSearch\elasticsearch‐6.2.1\data

path.logs: D:\ElasticSearch\elasticsearch‐6.2.1\logs

http.cors.enabled: true

http.cors.allow‐origin: /.*/

注意path.datapath.logs路径配置正确。

常用的配置项如下:

cluster.name:配置elasticsearch的集群名称,默认是elasticsearch。建议修改成一个有意义的名称。

node.name:节点名,通常一台物理服务器就是一个节点,es会默认随机指定一个名字,建议指定一个有意义的名称,方便管理一个或多个节点组成一个cluster集群,集群是一个逻辑的概念,节点是物理概念,后边章节会详细介绍。

path.conf: 设置配置文件的存储路径,tarzip包安装默认在es根目录下的confifig文件夹,rpm安装默认在/etc/elasticsearch path.data: 设置索引数据的存储路径,默认是es根目录下的data文件夹,可以设置多个存储路径,用逗号隔开。 path.logs: 设置日志文件的存储路径,默认是es根目录下的logs文件夹 path.plugins: 设置插件的存放路径,默认是es根目录下的plugins文件夹

bootstrap.memory_lock: true 设置为true可以锁住ES使用的内存,避免内存与swap分区交换数据。

network.host: 设置绑定主机的ip地址,设置为0.0.0.0表示绑定任何ip,允许外网访问,生产环境建议设置为具体的iphttp.port: 9200 设置对外服务的http端口,默认为9200

transport.tcp.port: 9300 集群结点之间通信端口node.master: 指定该节点是否有资格被选举成为master结点,默认是true,如果原来的master宕机会重新选举新的masternode.data: 指定该节点是否存储索引数据,默认为truediscovery.zen.ping.unicast.hosts: ["host1:port", "host2:port", "..."] 设置集群中master节点的初始列表。 discovery.zen.ping.timeout: 3s 设置ES自动发现节点连接超时的时间,默认为3秒,如果网络延迟高可设置大些。

discovery.zen.minimum_master_nodes:主结点数量的最少值 ,此值的公式为:(master_eligible_nodes / 2) + 1 ,比如:有3个符合要求的主结点,那么这里要设置为2

node.max_local_storage_nodes:单机允许的最大存储结点数,通常单机启动一个结点建议设置为1,开发环境如果单机启动多个节点可设置大于1.

2.2.3 jvm.options

设置最小及最大的JVM堆内存大小:

jvm.options中设置 -Xms-Xmx

1) 两个值设置为相等

2) 将 Xmx 设置为不超过物理内存的一半。

2.2.4 log4j2.properties

日志文件设置,ES使用log4j,注意日志级别的配置。

ES启动

进入bin目录,在cmd下运行:elasticsearch.bat

浏览器输入:http://localhost:9200

显示结果如下(配置不同内容则不同)说明ES启动成功:

创建索引库

ES的索引库是一个逻辑概念,它包括了分词列表及文档列表,同一个索引库中存储了相同类型的文档。它就相当于MySQL中的表,或相当于Mongodb中的集合。

关于索引这个语:

索引(名词):ES是基于Lucene构建的一个搜索服务,它要从索引库搜索符合条件索引数据。

索引(动词):索引库刚创建起来是空的,将数据添加到索引库的过程称为索引。

下边介绍两种创建索引库的方法,它们的工作原理是相同的,都是客户端向ES服务发送命令。

使用postmancurl这样的工具创建:

put http://localhost:9200/索引库名称

{

     "settings": {

          "index": {

               "number_of_shards": 1,

               "number_of_replicas": 0

          }

     }

}

number_of_shards:设置分片的数量,在集群中通常设置多个分片,表示一个索引库将拆分成多片分别存储不同 的结点,提高了ES的处理能力和高可用性,入门程序使用单机环境,这里设置为1

number_of_replicas:设置副本的数量,设置副本是为了提高ES的高可靠性,单机环境设置为0.

如下是创建的例子,创建xc_course索引库,共1个分片,0个副本:

概念说明

在索引中每个文档都包括了一个或多个field,创建映射就是向索引库中创建field的过程,下边是documentfield与关系数据库的概念的类比:

文档(Document----------------Row记录

字段(Field-------------------Columns

注意:6.0之前的版本有type(类型)概念,type相当于关系数据库的表,ES官方将在ES9.0版本中彻底删除type

上边讲的创建索引库相当于关系数据库中的数据库还是表?

1、如果相当于数据库就表示一个索引库可以创建很多不同类型的文档,这在ES中也是允许的。

2、如果相当于表就表示一个索引库只能存储相同类型的文档,ES官方建议 在一个索引库中只存储相同类型的文档。

3.2.2 创建映射

我们要把课程信息存储到ES中,这里我们创建课程信息的映射,先来一个简单的映射,如下:

发送:post http://localhost:9200/索引库名称/类型名称/_mapping

创建类型为xc_course的映射,共包括三个字段:namedescriptionstudymondel

由于ES6.0版本还没有将type彻底删除,所以暂时把type起一个没有特殊意义的名字。

post 请求:http://localhost:9200/xc_course/doc/_mapping

表示:在xc_course索引库下的doc类型下创建映射。doc是类型名,可以自定义,在ES6.0中要弱化类型的概念, 给它起一个没有具体业务意义的名称。

{

         "properties": {

                  "name": {

                           "type": "text"

                  },

                  "description": {

                           "type": "text"

                  },

                  "studymodel": {

                           "type": "keyword"

                  }

         }

}

映射创建成功在kibon中查询

 

创建文档

ES中的文档相当于MySQL数据库表中的记录。

发送:put Post http://localhost:9200/xc_course/doc/id

(如果不指定idES会自动生成ID

http://localhost:9200/xc_course/doc/4028e58161bcf7f40161bcf8b77c0000

{

       "name": "Bootstrap开发框架",

       "description": "Bootstrap是由Twitter推出的一个前台页面开发框架,在行业之中使用较为广泛。此开发框架包 含了大量的CSS、JS程序代码,可以帮助开发者(尤其是不擅长页面开发的程序人员)轻松的实现一个不受浏览器限制的 精美界面效果。",

       "studymodel": "201001"

}

使用postman测试:

搜索文档

1、根据课程id查询文档

发送:get http://localhost:9200/xc_course/doc/4028e58161bcf7f40161bcf8b77c0000

使用postman测试:

2、查询所有记录

发送 get http://localhost:9200/xc_course/doc/_search

3、查询名称中包括spring 关键字的的记录

发送:get http://localhost:9200/xc_course/doc/_search?q=name:bootstrap

4、查询学习模式为201001的记录

发送 get http://localhost:9200/xc_course/doc/_search?q=studymodel:201001

查询结果分析

分析上边查询结果:

{

         "took": 1,

         "timed_out": false,

         "_shards": {

                  "total": 1,

                  "successful": 1,

                  "skipped": 0,

                  "failed": 0

         },

         "hits": {

                  "total": 1,

                  "max_score": 0.2876821,

                  "hits": [{

                           "_index": "xc_course",

                           "_type": "doc",

                           "_id": "4028e58161bcf7f40161bcf8b77c0000",

                           "_score": 0.2876821,

                           "_source": {

                                    "name": "Bootstrap开发框架",

                                    "description": "Bootstrap是由Twitter推出的一个前台页面开发框架,在行业之中使用较 为广泛。此开发框架包含了大量的CSS、JS程序代码,可以帮助开发者(尤其是不擅长页面开发的程序人员)轻松的实现 一个不受浏览器限制的精美界面效果。",

                                    "studymodel": "201001"

                           }

                  }]

         }

}

took:本次操作花费的时间,单位为毫秒。

timed_out:请求是否超时

_shards:说明本次操作共搜索了哪些分片

hits:搜索命中的记录

hits.total : 符合条件的文档总数 hits.hits :匹配度较高的前N个文档

hits.max_score:文档匹配得分,这里为最高分

_score:每个文档都有一个匹配度得分,按照降序排列。

_source:显示了文档的原始内容。

测试分词器

在添加文档时会进行分词,索引中存放的就是一个一个的词(term),当你去搜索时就是拿关键字去匹配词,最终找到词关联的文档。

测试当前索引库使用的分词器:

post 发送:localhost:9200/_analyze

{"text":"测试分词器,后边是测试内容spring cloud实战"}

{"text":"中华人民共和国财政部"}

结果如下:

会发现分词的效果将 测试这个词拆分成两个单字,这是因为当前索引库使用的分词器对中文就是单字分词。

 

 

两种分词模式

ik分词器有两种分词模式:ik_max_wordik_smart模式。

1ik_max_word

会将文本做最细粒度的拆分,比如会将中华人民共和国人民大会堂拆分为中华人民共和国、中华人民、中华、 华人、人民共和国、人民、共和国、大会堂、大会、会堂等词语。

2ik_smart

会做最粗粒度的拆分,比如会将中华人民共和国人民大会堂拆分为中华人民共和国、人民大会堂。

测试两种分词模式:

发送:post localhost:9200/_analyze

{"text":"中华人民共和国人民大会堂","analyzer":"ik_smart" }

 映射维护方法

1、查询所有索引的映射:

GEThttp://localhost:9200/_mapping

2、创建映射

post 请求:http://localhost:9200/xc_course/doc/_mapping

一个例子:

{

         "properties": {

                  "name": {

                           "type": "text"

                  },

                  "description": {

                           "type": "text"

                  },

                  "studymodel": {

                           "type": "keyword"

                  }

         }

}

3、更新映射

映射创建成功可以添加新字段,已有字段不允许更新。

4、删除映射

通过删除索引来删除映射。

以delete方式

http://localhost:9200/xc_course/

 text文本字段

下图是ES6.2核心的字段类型如下:

字符串包括textkeyword两种类型:

1text

1analyzer

通过analyzer属性指定分词器。

下边指定name的字段类型为text,使用ik分词器的ik_max_word分词模式。

"name": {

     "type": "text",

     "analyzer": "ik_max_word"

}

上边指定了analyzer是指在索引和搜索都使用ik_max_word,如果单独想定义搜索时使用的分词器则可以通过 search_analyzer属性。   

对于ik分词器建议是索引时使用ik_max_word将  搜索内容进行细粒度分词,搜索时使用ik_smart提高搜索精确性。

"name": {

     "type": "text",

     "analyzer": "ik_max_word",

     "search_analyzer": "ik_smart"

}

2index

通过index属性指定是否索引。

默认为index=true,即要进行索引,只有进行索引才可以从索引库搜索到。

但是也有一些内容不需要索引,比如:商品图片地址只被用来展示图片,不进行搜索图片,此时可以将index设置为false

删除索引,重新创建映射,将picindex设置为false,尝试根据pic去搜索,结果搜索不到数据

"pic": {

"type": "text",

"index":false

}

 

测试

删除xc_course/doc下的映射

创建新映射:Post http://localhost:9200/xc_course/doc/_mapping

{

     "properties": {

          "name": {

               "type": "text",

               "analyzer": "ik_max_word",

               "search_analyzer": "ik_smart"

          },

          "description": {

               "type": "text",

               "analyzer": "ik_max_word",

               "search_analyzer": "ik_smart"

          },

          "pic": {

               "type": "text",

               "index": false

          },

          "studymodel": {

               "type": "text"

          }

     }

}

插入文档:

http://localhost:9200/xc_course/doc/4028e58161bcf7f40161bcf8b77c0000

{

         "name": "Bootstrap开发框架",

         "description": "Bootstrap是由Twitter推出的一个前台页面开发框架,在行业之中使用较为广泛。此开发框架包 含了大量的CSS、JS程序代码,可以帮助开发者(尤其是不擅长页面开发的程序人员)轻松的实现一个不受浏览器限制的 精美界面效果。",

         "pic": "group1/M00/00/01/wKhlQFqO4MmAOP53AAAcwDwm6SU490.jpg",

         "studymodel": "201002"

}

查询测试:

Get http://localhost:9200/xc_course/_search?q=name:开发

Get http://localhost:9200/xc_course/_search?q=description:开发

Get http://localhost:9200/xc_course/_search?

q=pic:group1/M00/00/01/wKhlQFqO4MmAOP53AAAcwDwm6SU490.jpg

Get http://localhost:9200/xc_course/_search?q=studymodel:201002

通过测试发现:namedescription都支持全文检索,pic不可作为查询条件。

 keyword关键字字段

上边介绍的text文本字段在映射时要设置分词器,keyword字段为关键字字段,通常搜索keyword是按照整体搜索,所以创建keyword字段的索引时是不进行分词的,比如:邮政编码、手机号码、身份证等。keyword字段通常用于过虑、排序、聚合等。

5.2.2.1测试

更改映射:

{

         "properties": {

                  "studymodel": {

                           "type": "keyword"

                  },

                  "name": {

                           "type": "keyword"

                  }

         }

}

插入文档:

{

"name": "java编程基础",

"description": "java语言是世界第一编程语言,在软件开发领域使用人数最多。",

"pic":"group1/M00/00/01/wKhlQFqO4MmAOP53AAAcwDwm6SU490.jpg",

"studymodel": "201001"

}

根据studymodel查询文档

搜索:http://localhost:9200/xc_course/_search?q=name:java

namekeyword类型,所以查询方式是精确查询。

5.2.3 date日期类型

日期类型不用设置分词器。

通常日期类型的字段用于排序。

1)format

通过format设置日期格式

例子:

下边的设置允许date字段存储年月日时分秒、年月日及毫秒三种格式。

{

         "properties": {

                  "timestamp": {

                           "type": "date",

                           "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd"

                  }

         }

}

插入文档:

Post :http://localhost:9200/xc_course/doc/3

{

"name": "spring开发基础",

"description": "spring java领域非常流行,java程序员都在用。",

"studymodel": "201001",

"pic":"group1/M00/00/01/wKhlQFqO4MmAOP53AAAcwDwm6SU490.jpg",

"timestamp":"2018‐07‐04 18:28:58"

}

数值类型

下边是ES支持的数值类型

1、尽量选择范围小的类型,提高搜索效率

2、对于浮点数尽量用比例因子,比如一个价格字段,单位为元,我们将比例因子设置为100这在ES中会按 分 存 储,映射如下:

"price": {

"type": "scaled_float",

"scaling_factor": 100

},

由于比例因子为100,如果我们输入的价格是23.45ES中会将23.45乘以100存储在ES中。

如果输入的价格是23.456ES会将23.456乘以100再取一个接近原始值的数,得出2346

使用比例因子的好处是整型比浮点型更易压缩,节省磁盘空间。

如果比例因子不适合,则从下表选择范围小的去用:

更新已有映射,并插入文档:

http://localhost:9200/xc_course/doc/3

{

"name": "spring开发基础",

"description": "spring java领域非常流行,java程序员都在用。",

"studymodel": "201001",

"pic":"group1/M00/00/01/wKhlQFqO4MmAOP53AAAcwDwm6SU490.jpg",

"timestamp":"2018‐07‐04 18:28:58",

"price":38.6

}

综合例子

创建如下映射

posthttp://localhost:9200/xc_course/doc/_mapping

{

         "properties": {

                  "description": {

                           "type": "text",

                           "analyzer": "ik_max_word",

                           "search_analyzer": "ik_smart"

                  },

                  "name": {

                           "type": "text",

                           "analyzer": "ik_max_word",

                           "search_analyzer": "ik_smart"

                  },

                  "pic": {

                           "type": "text",

                           "index": false

                  },

                  "price": {

                           "type": "float"

                  },

                  "studymodel": {

                           "type": "keyword"

                  },

                  "timestamp": {

                           "type": "date",

                           "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd"

                  }

         }

}

插入文档:

Post: http://localhost:9200/xc_course/doc/1

{

         "name": "Bootstrap开发",

         "description": "Bootstrap是由Twitter 推出的一个前台页面开发框架,是一个非常流行的开发框架,此框架集成了多种页面效果。此开发框架包含了大量 的CSS、JS程序代码,可以帮助开发者(尤其是不擅长页面开发的程序人员)轻松的实现一个不受浏览器限制的精 美界面效果。",

         "studymodel": "201002",

         "price": 38.6,

         "timestamp": "2018-04-25 19:11:35",

         "pic": "group1/M00/00/00/wKhlQFs6RCeAY0pHAAJx5ZjNDEM428.jpg"

}

 搭建工程

ES客户端

ES提供多种不同的客户端:

1TransportClient

ES提供的传统客户端,官方计划8.0版本删除此客户端。

2RestClient

RestClient是官方推荐使用的,它包括两种:Java Low Level REST ClientJava High Level REST Client

ES6.0之后提供 Java High Level REST Client, 两种客户端官方更推荐使用 Java High Level REST Client,不过当

前它还处于完善中,有些功能还没有。

本教程准备采用 Java High Level REST Client,如果它有不支持的功能,则使用Java Low Level REST Client

添加依赖:

创建搜索工程

创建搜索工程(maven工程):xc-service-search,添加RestHighLevelClient依赖及junit依赖。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

   <parent>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-parent</artifactId>

    <version>2.1.6.RELEASE</version>

</parent>

  

<groupId>com.zb</groupId>

<artifactId>my0709es</artifactId>

<version>1.0-SNAPSHOT</version>

<dependencies>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-web</artifactId>

    </dependency>

    <dependency>

        <groupId>org.elasticsearch.client</groupId>

        <artifactId>elasticsearch-rest-high-level-client</artifactId>

        <version>6.5.4</version>

    </dependency>

    <dependency>

        <groupId>org.elasticsearch</groupId>

        <artifactId>elasticsearch</artifactId>

        <version>6.5.4</version>

    </dependency>

</dependencies>


    <build>

        <plugins>

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

            </plugin>

        </plugins>

    </build>

  

</project>
 

2、配置文件

server:

  port: ${port:40100}

spring:

  application:

    name: esdemo

xc:

  elasticsearch:

    hostlist: ${eshostlist:192.168.1.110:9200}
 

3、配置类

创建com.zb.config包 

在其下创建配置类

package com.zb.config;

  

import org.apache.http.HttpHost;

import org.elasticsearch.client.RestClient;

import org.elasticsearch.client.RestHighLevelClient;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

  

@Configuration

public class ElasticsearchConfig {

    @Value("${xc.elasticsearch.hostlist}")

    private String hostlist;

  

    @Bean

    public RestHighLevelClient restHighLevelClient() {

        //解析hostlist配置信息

        String[] split = hostlist.split(",");

        //创建HttpHost数组,其中存放es主机和端口的配置信息

        HttpHost[] httpHostArray = new HttpHost[split.length];

        for (int i = 0; i < split.length; i++) {

            String item = split[i];

            httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");

        }

        //创建RestHighLevelClient客户端

        return new RestHighLevelClient(RestClient.builder(httpHostArray));

    }

  

    //项目主要使用RestHighLevelClient,对于低级的客户端暂时不用

    @Bean

    public RestClient restClient() {

        //解析hostlist配置信息

        String[] split = hostlist.split(",");

        //创建HttpHost数组,其中存放es主机和端口的配置信息

        HttpHost[] httpHostArray = new HttpHost[split.length];

        for (int i = 0; i < split.length; i++) {

            String item = split[i];

            httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");

        }

        return RestClient.builder(httpHostArray).build();

    }

}
 

创建索引库

API

创建索引:

put http://localhost:9200/索引名称

{

         "settings": {

                  "index": {

                           "number_of_shards": 1, #分片的数量

"number_of_replicas": 0 #副本数量

                  }

         }

}

创建映射:

发送:put http://localhost:9200/索引库名称/类型名称/_mapping

创建类型为xc_course的映射,共包括三个字段:namedescriptionstudymodel

http://localhost:9200/xc_course/doc/_mapping

{

         "properties": {

                  "name": {

                           "type": "text",

                           "analyzer": "ik_max_word",

                           "search_analyzer": "ik_smart"

                  },

                  "description": {

                           "type": "text",

                           "analyzer": "ik_max_word",

                           "search_analyzer": "ik_smart"

                  },

                  "studymodel": {

                           "type": "keyword"

                  },

                  "price": {

                           "type": "float"

                  },

                  "timestamp": {

                           "type": "date",

                           "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"

                  }

         }

}

 Java Client

@SpringBootTest

@RunWith(SpringRunner.class)

public class TestIndex {

    @Autowired

    private RestHighLevelClient restHighLevelClient;

    @Autowired

    private RestClient restClient;

    /*删除索引库*/

    @Test

    public void testDeleteIndex() {

        try {

            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("xc_course");

            DeleteIndexResponse deleteIndexResponse = restHighLevelClient.indices().delete(deleteIndexRequest);

            boolean acknowledged = deleteIndexResponse.isAcknowledged();

            System.out.println(acknowledged);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    //添加文档

    @Test

    public void testAddDoc() throws IOException {

        //准备json数据

        Map<String, Object> jsonMap = new HashMap<>();

        jsonMap.put("name", "spring cloud实战");

        jsonMap.put("description", "本课程主要从四个章节进行讲解: 1.微服务架构入门 2.spring cloud基础入门 3.实战Spring Boot 4.注册中心eureka。");

        jsonMap.put("studymodel", "201001");

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        jsonMap.put("timestamp", dateFormat.format(new Date()));

        jsonMap.put("price", 5.6f);

        //索引请求对象

        IndexRequest indexRequest = new IndexRequest("nj_course", "doc");

        //指定索引文档内容

        indexRequest.source(jsonMap);

        //索引响应对象

        IndexResponse indexResponse = restHighLevelClient.index(indexRequest);

        //获取响应结果

        DocWriteResponse.Result result = indexResponse.getResult();

        System.out.println(result);

    }

    @Test

    public void testAddIndex() throws IOException {

        CreateIndexRequest createIndexRequest = new CreateIndexRequest("xc_course");

        createIndexRequest.settings(Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0));

        //设置映射

        createIndexRequest.mapping("doc", " {\n" +

                " \t\"properties\": {\n" +

                "           \"name\": {\n" +

                "              \"type\": \"text\",\n" +

                "              \"analyzer\":\"ik_max_word\",\n" +

                "              \"search_analyzer\":\"ik_smart\"\n" +

                "           },\n" +

                "           \"description\": {\n" +

                "              \"type\": \"text\",\n" +

                "              \"analyzer\":\"ik_max_word\",\n" +

                "              \"search_analyzer\":\"ik_smart\"\n" +

                "           },\n" +

                "           \"studymodel\": {\n" +

                "              \"type\": \"keyword\"\n" +

                "           },\n" +

                "           \"price\": {\n" +

                "              \"type\": \"float\"\n" +

                "           }\n" +

                "        }\n" +

                "}", XContentType.JSON);

        //创建索引操作客户端

        IndicesClient indices = restHighLevelClient.indices();

        //创建响应对象

        CreateIndexResponse createIndexResponse = indices.create(createIndexRequest);

        //得到响应结果

        boolean acknowledged = createIndexResponse.isAcknowledged();

        System.out.println(acknowledged);

    }

    @Test

    public void getDoc() throws IOException {

        GetRequest getRequest = new GetRequest(

                "nj_course",

                "doc",

                "rnynaWsBDjrihc96zXhk");

        GetResponse getResponse = restHighLevelClient.get(getRequest);

        boolean exists = getResponse.isExists();

        Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();

        System.out.println(sourceAsMap);

    }

    //更新文档

    @Test

    public void updateDoc() throws IOException {

        UpdateRequest updateRequest = new UpdateRequest("nj_course", "doc",

                "rnynaWsBDjrihc96zXhk");

        Map<String, String> map = new HashMap<>();

        map.put("name", "jsp boot");

        updateRequest.doc(map);

        UpdateResponse update = restHighLevelClient.update(updateRequest);

        RestStatus status = update.status();

        System.out.println(status);

}

//根据id删除文档

@Test

public void testDelDoc() throws IOException {

//删除文档id

String id = "eqP_amQBKsGOdwJ4fHiC";

//删除索引请求对象

DeleteRequest deleteRequest = new DeleteRequest("xc_course","doc",id);

//响应对象

DeleteResponse deleteResponse = client.delete(deleteRequest);

//获取响应结果

DocWriteResponse.Result result = deleteResponse.getResult();

System.out.println(result);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值