侧边栏壁纸
博主头像
帮主の后花园博主等级

欢迎光临,开开心心每一天

  • 累计撰写 21 篇文章
  • 累计创建 5 个标签
  • 累计收到 3 条评论

目 录CONTENT

文章目录

ElasticSearch 入门

Gxbalun
2022-03-16 / 2 评论 / 3 点赞 / 1703 阅读 / 40859 字

ElasticSearch

概述

ElasticSeacher 是一个分布式、RESTful 风格的的搜索和数据分析引擎,能够解决不断涌现的各种用例。作为 Elastic Stack 的核心,它集中存储您的数据,帮助您发现意料之中以及意料之外的情况。

ElasticSearch,简称 ES,是一个开源的高扩展的分布式权威搜索引擎,是整个 Elastic Stack 技术栈的核心。他可以近乎实现存储、检索数据;本身扩展性很好,可以扩展到上百台服务器,处理 PB 级别的数据。

基本操作

RESTful

REST 指的是一组架构约束条件和原则。满足这些约束条件和原则的应用程序或设计就是 RESTful。Web 应用程序最重要的 REST 原则是,客户端和服务器之间的交互在请求之间是无状态的。从客户端到服务器的每个请求都必须包含理解请求所必需的信息。如果服务器在请求之间的任何时间点重启,客户端不会得到通知。此外,无状态请求可以由任何可用服务器回答,这十分适合云计算之类的环境。客户端可以缓存数据以改进性能。

在服务器端,应用程序状态和功能可以分为各种资源。资源是一个有趣的概念实体,它向客户端公开。资源的例子有:应用程序对象、数据库记录、算法等等。每个资源都使用 URI (Universal Resource Identifier) 得到一个唯一的地址。所有资源都共享统一的接口,以便在客户端和服务器之间传输状态。使用的是标准的 HTTP 方法,比如 GET、PUT、POST 和DELETE。

在 REST 样式的 Web 服务中,每个资源都有一个地址。资源本身都是方法调用的目标,方法列表对所有资源都是一样的。这些方法都是标准方法,包括 HTTP GET、POST、PUT、DELETE,还可能包括 HEAD 和 OPTIONS。简单的理解就是,如果想要访问互联网上的资源,就必须向资源所在的服务器发出请求,请求体中必须包含资源的网络路径,以及对资源进行的操作(增删改查)。

数据格式

Elasticsearch 是面向文档型数据库,一条数据在这里就是一个文档。为了方便大家理解,我们将 Elasticsearch 里存储文档数据和关系型数据库 MySQL 存储数据的概念进行一个类比:

image-20220314131740553

ES 里的 Index 可以看做一个库,而 Types 相当于表,Documents 相当于表的行。

这里 Types 的概念以及逐渐弱化,ES 6.X 中,一个 index 下已经只能包含一个 Type,ES 7.X 中,Type 的概念已经被删除了。

用 JSON 作为文档序列化的格式,比如一条用户信息:

{
    "name" : "John",
    "sex" : "Male",
    "age" : 25,
    "birthDate" : "1990/05/01",
    "about" : "I love to go rock climing",
    "interests" : ["sports","music"]
}

HTTP 操作

索引操作

创建索引

对比关系型数据库,创建索引就等同于创建数据库

向 ES 服务器发 PUT 请求:http://127.0.0.1:9200/shopping

image-20220314132556372

服务器返回响应

image-20220314132625246

{
    "acknowledged"【响应结果】: true,
    "shards_acknowledged"【分片结果】: true,
    "index"【索引名称】: "shopping"
}

如果重复添加,将返回错误信息:

image-20220314133052223

查看所有索引

向 ES 服务器发送 GET 请求:http://localhost:9200/_cat/indices?v

image-20220314133234729

请求路径中,_cat 表示查看的意思,indices 表示索引,所以整体含义就是查看当前 ES 服务器的所有索引。返回结果如下:

image-20220314133509024

表头 含义
health 当前服务器健康状态:green(集群完整) yellow(单点正常、集群不完整) red(单点不正常)
status 索引打开、关闭状态
index 索引名
uuid 索引统一编号
pri 主分片数量
rep 副本数量
docs.count 可用文档数量
docs.deleted 文档删除状态(逻辑删除)
store.size 主分片和副分片整体占用空间大小
pri.store.size 主分片占用空间大小

查看单个索引

向 ES 服务器发送 GET 请求:http://127.0.0.1:9200/shopping

image-20220314134201456

查看索引向 ES 服务器发送的请求路径和创建索引是一致的。但是 HTTP 方法不一致。这里可以体会一下 RESTful 的意义。

返回结果:

image-20220314134225859

{
    "shopping"【索引名】: { 
 		"aliases"【别名】: {},
 		"mappings"【映射】: {},
         "settings"【设置】: {
 			"index"【设置 - 索引】: {
                 "creation_date"【设置 - 索引 - 创建时间】: "1614265373911",
                 "number_of_shards"【设置 - 索引 - 主分片数量】: "1",
                 "number_of_replicas"【设置 - 索引 - 副分片数量】: "1",
                 "uuid"【设置 - 索引 - 唯一标识】: "eI5wemRERTumxGCc1bAk2A",
                 "version"【设置 - 索引 - 版本】: {
                 "created": "7080099"
                 },
			    "provided_name"【设置 - 索引 - 名称】: "shopping"
 			}
 		}
 	} 
}

删除索引

向 ES 服务器发 DELETE 请求:http://127.0.0.1:9200/shopping

image-20220314134646324

返回结果:

image-20220314134701459

重新访问索引时,服务器返回结果:索引不存在

image-20220314135153070

文档操作

创建文档

索引已经创建好了,接下来我们创建文档,并添加数据。这里的文档可以类比为关系型数据库中的表数据,添加的数据格式为 JSON 格式。

向 ES 服务器发送 POST 请求:http://127.0.0.1:9200/shopping/_doc

请求体内容为:

{
    "title": "小米手机",
    "categocy": "小米",
    "images": "http://www.gulixueyuan.com/xm.jpg",
    "price": 3999
}

image-20220314140115578

服务器响应结果如下:

image-20220314140240513

{
    "_index"【索引】: "shopping",
	"_type"【类型-文档】: "_doc",
	"_id"【唯一标识】: "Xhsa2ncBlvF_7lxyCE9G", #可以类比为 MySQL 中的主键,随机生成
	"_version"【版本】: 1,
	"result"【结果】: "created", #这里的 create 表示创建成功
	"_shards"【分片】: {
		"total"【分片 - 总数】: 2,
         "successful"【分片 - 成功】: 1,
         "failed"【分片 - 失败】: 0
	},
	"_seq_no": 0,
	"_primary_term": 1
}

上面的数据创建后,由于没有指定数据唯一标识(ID),默认情况下,ES 服务器会随机生成一个。

如果想要自定义随即标识,需要在创建时指定:http://127.0.0.1:9200/shopping/_doc/1

image-20220314140717485

返回结果:

image-20220314141636526

查看文档

查看文档时,需要指明文档的唯一性标识,类似于 MySQL 中数据的主键查询。

向 ES 服务器发 GET 请求:http://127.0.0.1:9200/shopping/phone/1

image-20220314141715389

服务器返回结果:

image-20220314141736019

{
    "_index"【索引】: "shopping",
    "_type"【文档类型】: "_doc",
    "_id": "1",
    "_version": 2,
    "_seq_no": 2,
    "_primary_term": 2,
    "found"【查询结果】: true, # true 表示查找到,false 表示未查找到
    "_source"【文档源信息】: {
        "title": "华为手机",
        "category": "华为",
        "images": "http://www.gulixueyuan.com/hw.jpg",
        "price": 5999.00
	}
}

修改文档

和新增文档一样,输入相同的 URL 地址请求,如果请求体变化,会将原有的数据内容覆盖。

向 ES 服务器发送 POST 请求:http://127.0.0.1:9200/shopping/phone/1

请求体内容:

{
    "title": "华为手机",
    "categocy": "华为",
    "images": "http://www.gulixueyuan.com/hw.jpg",
    "price": 4999
}

image-20220314142355576

服务器返回结果:

image-20220314142429645

{
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1",
    "_version"【版本】: 2,
    "result"【结果】: "updated", # updated 表示数据被更新
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 2,
    "_primary_term": 2
}

修改字段

修改数据时,也可以只修改某一条数据的局部信息

向 ES 服务器发送 POST 请求:http://127.0.0.1:9200/shopping/_update/1

请求体内容为:

{
    "doc": {
        "price":3000
    }
}

image-20220314142823153

服务器返回结果:

image-20220314142856435

再次查询,文档数据已更新:

image-20220314144908755

删除文档

删除一个文档不会立即从磁盘上移除,它只是被标记成已删除(逻辑删除)。

向 ES 服务器发送 DELETE 请求:http://127.0.0.1::9200/shopping/phone/1

image-20220314145308015

删除成功,服务器响应结果:

image-20220314145339055

{
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1",
    "_version"【版本】: 4, #对数据的操作,都会更新版本
    "result"【结果】: "deleted", # deleted 表示数据被标记为删除
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 4,
    "_primary_term": 2
}

删除后再查询当前文档信息:

image-20220314145646541

image-20220314145718479

条件删除文档

一般删除数据都是根据文档的唯一性标识进行删除,实际操作时,也可以根据条件对多条数据进行删除

首先分别增加多条数据:

{
    "title":"小米手机",
    "category":"小米",
    "images":"http://www.gulixueyuan.com/xm.jpg",
    "price":4000.00
}
和
{
    "title":"华为手机",
    "category":"华为",
    "images":"http://www.gulixueyuan.com/hw.jpg",
    "price":4000.00
}

向 ES 服务器发送 POST 请求:http://127.0.0.1:9200/shopping/_delete_by_query

请求体内容为:

{
    "query":{
        "match":{
            "price":4000
        }
    }
}

image-20220314150320428

删除成功后,服务器响应结果:

image-20220314150417981

{
    "took"【耗时】: 1228,
    "timed_out"【是否超时】: false,
    "total"【总数】: 1,
    "deleted"【删除数量】: 1,
    "batches": 1,
    "version_conflicts": 0,
    "noops": 0,
    "retries": {
        "bulk": 0,
        "search": 0
    },
    "throttled_millis": 0,
    "requests_per_second": -1.0,
    "throttled_until_millis": 0,
    "failures": []
}

映射操作

有了索引库,等于有了数据库中的 database。

接下来就需要建立索引库中的映射了,类似于数据库中的表结构。创建数据库表需要设置字段名称,类型,长度,约束等;索引库也一样,需要知道这个类型下有哪些字段,每个字段有哪些约束信息,这就叫做映射。

创建映射

向 ES 服务器发送 PUT 请求:http://127.0.0.1:9200/student/_mapping

请求体内容为:

{
	"properties": {
		"name":{
            "type": "text",
            "index": true
		},
        "sex":{
            "type": "text",
            "index": false
		},
        "age":{
            "type": "long",
            "index": false
		}
	}
}

image-20220314151544830

服务器响应结果如下:

image-20220314151620050

映射数据说明:

  • 字段名:任意填写,下面指定许多属性,例如:title、subtitle、images、price
  • type:类型,es 中支持的数据类型非常丰富,说几个关键的:
    • String 类型:
      • text:可分词
      • keyword:不可分词,数据会作为完整字段进行匹配
    • Numerical:数值类型,分两类
      • 基本数据类型:long、integer、short、byte、double、float、half_float
      • 浮点数的高精度类型:scaled_float
      • Date:日期类型
      • Array:数组类型
      • Object:对象
  • index:是否索引,默认为 true,也就是说你不进行任何配置,所有字段都会被索引。
    • true:字段会被索引,则可以用来进行搜索
    • false:字段不会被索引,不能用来搜索
  • store:是否将数据进行独立存储,默认为 false

原始的文本会存储在 _source 里面,默认情况下其他提取出来的字段都不是独立存储的,是从_source 里面提取出来的。当然你也可以独立的存储某个字段,只要设置 “store”: true 即可,获取独立存储的字段要比从_source 中解析快得多,但是也会占用更多的空间,所以要根据实际业务需求来设置。

  • analyzer:分词器,这里的 ik_max_word 即使用 ik 分词器,后面会有专门的章节学习

查看映射

向 ES 服务器发送 GET 请求:http://127.0.0.1:9200/student/_mapping

image-20220314152507470

服务器响应结果如下:

image-20220314152601108

索引映射关联

向 ES 服务器发送 PUT 请求:http://127.0.0.1:9200/student1

image-20220314152912235服务器响应结果如下:

image-20220314152935359

高级查询

ES 提供了基于 JSON 提供完整的查询 DSL 来定义查询

定义数据:

# POST /student/_doc/1001
{
    "name": "zhangsan",
    "nickname": "zhangsan",
    "sex": "男",
    "age": 30
}
# POST /student/_doc/1002
{
    "name": "lisi",
    "nickname": "lisi",
    "sex": "男",
    "age": 20
}
# POST /student/_doc/1003
{
    "name": "wangwu",
    "nickname": "wangwu",
    "sex": "女",
    "age": 40
}
# POST /student/_doc/1004
{
    "name": "zhangsan1",
    "nickname": "zhangsan1",
    "sex": "女",
    "age": 50
}
# POST /student/_doc/1005
{
    "name": "zhangsan2",
    "nickname": "zhangsan2",
    "sex": "女",
    "age": 30
}
查询所有文档

向 ES 服务器发送 GET 请求:http://127.0.0.1:9200/student/_search

{
    "query": {
        "match_all": {}
    }
}
# "query":这里的 query 代表一个查询对象,里面可以有不同的查询属性
# "match_all":查询类型,例如:match_all(代表查询所有), match,term , range 等等
# {查询条件
}:查询条件会根据类型的不同,写法也有差异

image-20220314154050509

服务器响应结果如下:

{
    "took": 1105,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 5,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "student",
                "_type": "_doc",
                "_id": "1001",
                "_score": 1.0,
                "_source": {
                    "name": "zhangsan",
                    "nickname": "zhangsan",
                    "sex": "男",
                    "age": 30
                }
            },
            {
                "_index": "student",
                "_type": "_doc",
                "_id": "1002",
                "_score": 1.0,
                "_source": {
                    "name": "lisi",
                    "nickname": "lisi",
                    "sex": "男",
                    "age": 20
                }
            },
            {
                "_index": "student",
                "_type": "_doc",
                "_id": "1003",
                "_score": 1.0,
                "_source": {
                    "name": "wangwu",
                    "nickname": "wangwu",
                    "sex": "女",
                    "age": 40
                }
            },
            {
                "_index": "student",
                "_type": "_doc",
                "_id": "1004",
                "_score": 1.0,
                "_source": {
                    "name": "zhangsan1",
                    "nickname": "zhangsan1",
                    "sex": "女",
                    "age": 50
                }
            },
            {
                "_index": "student",
                "_type": "_doc",
                "_id": "1005",
                "_score": 1.0,
                "_source": {
                    "name": "zhangsan2",
                    "nickname": "zhangsan2",
                    "sex": "女",
                    "age": 30
                }
            }
        ]
    }
}
{
    "took【查询花费时间,单位毫秒】": 1116,
    "timed_out【是否超时】": false,
    "_shards【分片信息】": {
        "total【总数】": 1,
        "successful【成功】": 1,
        "skipped【忽略】": 0,
        "failed【失败】": 0
    },
    "hits【搜索命中结果】": {
        "total"【搜索条件匹配的文档总数】: {
            "value"【总命中计数的值】: 3,
            "relation"【计数规则】: "eq" # eq 表示计数准确, gte 表示计数不准确
        },
        "max_score【匹配度分值】": 1.0,
        "hits【命中结果集合】": [
		 。。。
    	]
	}
}
匹配查询

match 匹配类型查询,会把查询条件进行分词,然后进行查询,多个词条之间是 or 的关系。

向 ES 服务器发送 GET 请求:http://127.0.0.1:9200/student/_search

{
    "query":{
        "match":{
            "name":"zhangsan"
        }
    }
}

image-20220314154632796

服务器响应结果为:

image-20220314154702327

字段查询

……

ElasticSearch 使用 JAVA API 实现 索引、映射、文档操作

1.添加依赖

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.8.0</version>
        </dependency>
        <!-- elasticsearch 的客户端 -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.8.0</version>
        </dependency>
        <!-- elasticsearch 依赖 2.x 的 log4j -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.9</version>
        </dependency>
        <!-- junit 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

2.创建 ES 客户端配置类

配置好后在 Controller 层注入后直接调用

package com.bl.es.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost",9200,"http")
                )
        );
        return client;
    }

}

自动注入

 @Autowired
 public RestHighLevelClient restHighLevelClient;

3.索引操作

3.1 创建索引

public void CreateIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("game");
        CreateIndexResponse response = restHighLevelClient.indices().create(request,RequestOptions.DEFAULT);
        boolean status = response.isAcknowledged();
        System.out.println("索引操作:" + status);
        restHighLevelClient.close();
    }

3.2 获取索引

public void getIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest();
        request.indices("user");
        GetIndexResponse response = restHighLevelClient.indices().get(request,RequestOptions.DEFAULT);
        System.out.println(response.getAliases());
        System.out.println(response.getMappings());
        System.out.println(response.getSettings());
        restHighLevelClient.close();
    }

3.3 删除索引

public void deleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("game");
        AcknowledgedResponse response = restHighLevelClient.indices().delete(request,RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());
        restHighLevelClient.close();
    }

4.文档操作

4.1 创建文档

public void CreateDoc() throws IOException {
        //创建文档(请求对象)
        IndexRequest request = new IndexRequest();

        //设置索引及索引中文档的唯一性标识id(若不指定,es会默认随机生成一个id)
        request.index("user").id("1");

        //创建数据对象(文档内容)
        User user = new User();
        user.setName("小红");
        user.setAge(18);

        //向es中插入数据,必须将数据格式转换为JSON
        ObjectMapper objectMapper = new ObjectMapper();
        String userJSON = objectMapper.writeValueAsString(user);
        request.source(userJSON,XContentType.JSON);

        //发送请求
        IndexResponse response = restHighLevelClient.index(request,RequestOptions.DEFAULT);
        System.out.println(response.getResult());
        restHighLevelClient.close();
    }

4.2 修改文档

public void DocUpdate() throws IOException {
        //修改文档请求对象
        UpdateRequest request = new UpdateRequest();

        //配置修改参数    表示要修改user索引中id为1的文档内容
        request.index("user").id("1");

        //将修改后的内容,以JSON格式写入请求中
        request.doc(XContentType.JSON,"name","小红红","age",81);

        //发送请求
        UpdateResponse response = restHighLevelClient.update(request,RequestOptions.DEFAULT);
        System.out.println(response.getResult());
        restHighLevelClient.close();
    }

4.3 查看文档

public void DocSearch() throws IOException {
        GetRequest request = new GetRequest();
        request.index("user").id("1");
        GetResponse response = restHighLevelClient.get(request,RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());
        restHighLevelClient.close();
    }

4.4 删除文档

public void deleteDoc() throws IOException {
        DeleteRequest request = new DeleteRequest().index("user").id("1");
        DeleteResponse response = restHighLevelClient.delete(request,RequestOptions.DEFAULT);
        System.out.println(response.getResult());
        restHighLevelClient.close();
    }

4.5 批量创建文档

public void DocInsertBatch() throws IOException {
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest().index("user").id("2").source(XContentType.JSON,"name","小军","age",21));
        request.add(new IndexRequest().index("user").id("3").source(XContentType.JSON,"name","小马","age",23));
        request.add(new IndexRequest().index("user").id("4").source(XContentType.JSON,"name","张三","age",56));
        BulkResponse response = restHighLevelClient.bulk(request,RequestOptions.DEFAULT);
        System.out.println(response.getTook());
        restHighLevelClient.close();
    }

4.6 批量删除文档

public void DocDeleteBatch() throws IOException {
        BulkRequest request = new BulkRequest();
        request.add(new DeleteRequest().index("user").id("2"));
        request.add(new DeleteRequest().index("user").id("3"));
        request.add(new DeleteRequest().index("user").id("4"));
        BulkResponse responses = restHighLevelClient.bulk(request,RequestOptions.DEFAULT);
        System.out.println(responses.getTook());
        System.out.println(responses.getItems());
        restHighLevelClient.close();
    }

5.查询操作

5.1 条件查询

查询 name 字段为 小马 的文档

public void DocQuery() throws IOException {
        SearchRequest request = new SearchRequest("user");
        request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("name","小马")));
        SearchResponse response = restHighLevelClient.search(request,RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        System.out.println(response.getTook());
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
        restHighLevelClient.close();
    }

5.2 分页查询

从第一条数据开始查询,每页显示2条

public void DocQueryfy() throws IOException {
        SearchRequest request = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        builder.from(0);
        builder.size(2);
        request.source(builder);
        SearchResponse response = restHighLevelClient.search(request,RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        System.out.println(response.getTook());
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
        restHighLevelClient.close();
    }

5.3 排序查询

按照 age 字段查询,结果倒叙排序

public void DocSortQuery() throws IOException {
        SearchRequest request = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        builder.sort("age", SortOrder.DESC);
        request.source(builder);
        SearchResponse response = restHighLevelClient.search(request,RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
        restHighLevelClient.close();
    }

5.4 过滤字段查询

过滤掉 age 字段

public void DocQuerygl() throws IOException {
        SearchRequest request = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        String[] includes = {};
        String[] excludes = {"age"};
        builder.fetchSource(includes,excludes);
        request.source(builder);
        SearchResponse response = restHighLevelClient.search(request,RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
        restHighLevelClient.close();
    }

5.5 组合条件查询

查询 年龄=18 或 name=张三 的文档内容

public void DocQueryzh() throws IOException {
        SearchRequest request = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.should(QueryBuilders.matchQuery("age",18));
        boolQueryBuilder.should(QueryBuilders.matchQuery("name","张三"));
        builder.query(boolQueryBuilder);
        request.source(builder);
        SearchResponse response = restHighLevelClient.search(request,RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
        restHighLevelClient.close();
    }

5.6 范围查询

查询年龄age字段大于等于18,小于25的文档内容

public void DocQueryfw() throws IOException {
        SearchRequest request = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");
        rangeQueryBuilder.gte(18);
        rangeQueryBuilder.lt(25);
        builder.query(rangeQueryBuilder);
        request.source(builder);
        SearchResponse response = restHighLevelClient.search(request,RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
        restHighLevelClient.close();
    }

5.7 模糊查询

public void DocQuerymh() throws IOException {
        SearchRequest request = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.fuzzyQuery("name","小张").fuzziness(Fuzziness.ONE));
        //最后这个枚举类型 ONE ,表示查询结果中允许与我定义的name字段为 小张 相差一个字符
        request.source(builder);
        SearchResponse response = restHighLevelClient.search(request,RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
        restHighLevelClient.close();
    }

5.8 聚合查询

public void DocQueryjh() throws IOException {
        SearchRequest request = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        AggregationBuilder aggregationBuilder = AggregationBuilders.max("age").field("age");
        builder.aggregation(aggregationBuilder);
        request.source(builder);
        SearchResponse response = restHighLevelClient.search(request,RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
        restHighLevelClient.close();
    }

5.9 分组查询

public void DocQueryfz() throws IOException {
        SearchRequest request = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        AggregationBuilder aggregationBuilder = AggregationBuilders.terms("age").field("age");
        builder.aggregation(aggregationBuilder);
        request.source(builder);
        SearchResponse response = restHighLevelClient.search(request,RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
        restHighLevelClient.close();
    }

5.10 Bool查询

public void DocQuerybl() throws IOException {
        SearchRequest request = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("age","18"));
        boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name","张三"));
        //boolQueryBuilder.should(QueryBuilders.matchQuery("age","18"));
        builder.query(boolQueryBuilder);
        request.source(builder);
        SearchResponse response = click.search(request,RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
        click.close();
    }

5.11 高亮查询

public void DocQuerygl() throws IOException {
        SearchRequest request = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name.keyword","张三");
        builder.query(termsQueryBuilder);
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("name");
        builder.highlighter(highlightBuilder);
        request.source(builder);
        SearchResponse response = click.search(request,RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            System.out.println(highlightFields);
        }
        click.close();
    }

更多内容:https://www.kuangstudy.com/bbs/1354069127022583809

3

评论区