目录
1. Elasticsearch的下载和安装
1.1 下载
官方地址:https://www.elastic.co/cn/
下载地址::https://www.elastic.co/cn/downloads/past-releases#elasticsearch
选择对应的版本下载即可
1.2 安装
在Windows版本下直接解压到目录,即可完成安装。
将Bin文件夹加入到环境变量中,如果电脑的环境是JDK 11的话就可以直接点击elasticsearch.bat来启动ES服务。
打开浏览器,输入地址:http://localhost:9200,测试结果
注意:9300 端口为 Elasticsearch 集群间组件的通信端口,9200 端口为浏览器访问的 http 协议 RESTful 端口。
1.3 踩坑
当运行elasticsearch.bat后提示Java版本太老,elasticsearch需要JDK11的环境,所以会出现启动报错的情况。但是好在elasticsearch的文件目录中内置的对应的JDK文件,我们只需要修改一下运行环境即可。
在bin文件夹中找到elasticsearch-env.bat文件,找到下面语句并进行操作,就能启动成功。
在if "%JAVA_HOME%" == "" (...)
这部分上方 进行添加
set JAVA_HOME="%ES_HOME%\jdk"
2. 数据格式
Elasticsearch是面向文档型数据库,一条数据在这里就是一个文档。为了方便大家理解我们将Elasticsearch和MySql数据库来进行类比。
其中Type的概念已经逐渐弱化,在Elasticsearch 7.X 中这个概念已经被删除了。
3. Http操作
3.1 索引操作
3.1.1 创建索引
创建索引在传统的数据库中对应的是创建数据库。
在Postman中向ES服务器发送PUT请求,直接创建索引,连接和示意图如下:
http://127.0.0.1:9200/damon
"acknowledged"【响应结果】: true, # true 操作成功
"shards_acknowledged"【分片结果】: true, # 分片操作成功
"index"【索引名称】: "shopping"
如果反复添加索引会返回错误信息:
3.1.2 查看所有索引
在Postman中通过使用GET请求来查看存在的索引,连接和结果如下:
http://127.0.0.1:9200/_cat/indices?v
_cat表示查看的意思,indices表示索引的意思,总体意思就是查看索引。
3.1.3 查看单个索引
查看单个索引的请求路径和创建索引的请求路径是一致的,只是查询单个索引的HTTP方法使用的是GET请求。
http://127.0.0.1:9200/damon
"shopping"【索引名】,"aliases"【别名】,"mappings"【映射】,"settings"【设置】,"index"【设置 - 索引】,"creation_date"【设置 - 索引 - 创建时间】,"number_of_shards"【设置 - 索引 - 主分片数量】,"number_of_replicas"【设置 - 索引 - 副分片数量】,"uuid"【设置 - 索引 - 唯一标识】,"version"【设置 - 索引 - 版本】,"provided_name"【设置 - 索引 - 名称】
3.1.4 删除索引
请求路径和创建索引以及查询单个索引是相同的
http://127.0.0.1:9200/damon
3.2 文档操作
3.2.1 创建文档
在索引里面添加文档,这里的文档就相当于是关系型数据库的表数据,添加的格式为JSON格式。
注意:创建文档一定要使用POST请求!!!
http://127.0.0.1:9200/damon/_doc
"_type"【类型-文档】: "_doc"
"_id"【唯一标识】: "Xhsa2ncBlvF_7lxyCE9G", #可以类比为 MySQL 中的主键,随机生成
指定唯一标识创建文档:在_doc后面加上 / 指定标识,此时请求类型可用为PUT。
http://127.0.0.1:9200/damon/_doc/dadada
3.2.2 查看文档
向ES服务器发送GET请求,并在请求路径中指定唯一标识,即主键。
请求路径和创建文档相同,请求方式变为GET。
http://127.0.0.1:9200/damon/_doc/dadada
3.2.3 修改文档
和新增文档一样,输入相同的 URL 地址请求,如果请求体变化,会将原有的数据内容覆盖 在 Postman 中,向 ES 服务器发 POST 请求 :
http://127.0.0.1:9200/damon/_doc/dadada
3.2.4 修改字段
在 Postman 中,向 ES 服务器发 POST 请求:
http://127.0.0.1:9200/damon/_update/dadada
3.2.5 删除文档
删除一个文档不会立即从磁盘上移除,它只是被标记成已删除(逻辑删除)。
在 Postman 中,向 ES 服务器发 DELETE 请求:
http://127.0.0.1:9200/damon/_doc/dadada
删除一个不存在的文档,在“result”处会提示“not_found”。
3.2.6 条件删除文档
一般删除数据都是根据文档的唯一性标识进行删除,实际操作时,也可以根据条件对多条数 据进行删除。
增加多条数据:
{
"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/damon/_doc/_delete_by_query
请求体为:
{
"query":{
"match":{
"price":4000.00
}
}
}
实现对价格为4000的文档进行删除
3.3 映射操作
接下来就需要建索引库(index)中的映射了,类似于数据库(database)中的表结构(table)。 创建数据库表需要设置字段名称,类型,长度,约束等;索引库也一样,需要知道这个类型 下有哪些字段,每个字段有哪些约束信息,这就叫做映射(mapping)。
3.3.1 创建映射
首先先创建student索引,然后在 Postman 中,向 ES 服务器发 PUT 请求:
http://127.0.0.1:9200/student/_mapping
字段名:任意填写,下面包含很多属性
type:类型
String:
text:可分词
keyword:不可分词,数据会作为完整字段进行匹配
Numerical:数值类型,分两类
基本数据类型:long,integer,short,byte,double,float,half_float
浮点数的高精度类型:scaled_float
Date:日期类型
Array:数组类型
Object:对象
index:是否索引,默认为true,也就是说你不进行任何配置,所有字段都会被索引。
store:是否将数据进行独立存储,默认为 false。
analyzer:分词器,这里的 ik_max_word 即使用 ik 分词器
3.3.2 查看映射
Postman 中,向 ES 服务器发 GET 请求:
http://127.0.0.1:9200/student/_mapping
3.3.3 索引映射关联
在 Postman 中,向 ES 服务器发 PUT 请求:
http://127.0.0.1:9200/student1
{
"settings": {},
"mappings": {
"properties": {
"name":{
"type": "text",
"index": true
},
"sex":{
"type": "text",
"index": false
},
"age":{
"type": "long",
"index": false
}
}
}
}
3.4 高级查询
Elasticsearch 提供了基于 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
}
3.4.1 查询所有文档
在 Postman 中,向 ES 服务器发 GET 请求 :
http://127.0.0.1:9200/student/_search
{
"query": {
"match_all": {}
}
}
# "query":这里的 query 代表一个查询对象,里面可以有不同的查询属性
# "match_all":查询类型,例如:match_all(代表查询所有), match,term , range 等等
# {查询条件}:查询条件会根据类型的不同,写法也有差异
结果:将所有数据全部显示
{
"took【查询花费时间,单位毫秒】" : 952,
"timed_out【是否超时】" : false,
"_shards【分片信息】" : {
"total【总数】" : 1,
"successful【成功】" : 1,
"skipped【忽略】" : 0,
"failed【失败】" : 0
},
"hits【搜索命中结果】" : {
"total"【搜索条件匹配的文档总数】: {
"value"【总命中计数的值】: 5,
"relation"【计数规则】: "eq" # eq 表示计数准确, gte 表示计数不准确
},
"max_score【匹配度分值】" : 1.0,
"hits【命中结果集合】" : [
。。。
}
]
}
}
3.4.2 匹配查询
Match 匹配类型查询,会把查询条件进行分词,然后进行查询,多个词条之间是 or 的关系,在 Postman 中,向 ES 服务器发 GET 请求。
http://127.0.0.1:9200/student/_search
{
"query": {
"match": {
"name":"zhangsan"
}
}
}
命中结果
3.4.3 字段匹配查询
multi_match 与 match 类似,不同的是它可以在多个字段中查询。 在 Postman 中,向 ES 服务器发 GET 请求:
http://127.0.0.1:9200/student/_search
{
"query": {
"multi_match": {
"query": "zhangsan",
"fields": ["name","nickname"]
}
}
}
3.4.4 关键字精确查询
term 查询,精确的关键词匹配查询,不对查询条件进行分词。 在 Postman 中,向 ES 服务器发 GET 请求 :
http://127.0.0.1:9200/student/_search
{
"query": {
"term": {
"name": {
"value": "zhangsan"
}
}
}
}
3.4.5 多关键字查询
terms 查询和 term 查询一样,但它允许你指定多值进行匹配。 如果这个字段包含了指定值中的任何一个值,那么这个文档满足条件,类似于 mysql 的 in 。
Postman 中,向 ES 服务器发 GET 请求:
http://127.0.0.1:9200/student/_search
{
"query": {
"terms": {
"name": ["zhangsan","lisi"]
}
}
}
3.4.6 指定字段查询
默认情况下,Elasticsearch 在搜索的结果中,会把文档中保存在_source 的所有字段都返回。 如果我们只想获取其中的部分字段,我们可以添加_source 的过滤
在 Postman 中,向 ES 服务器发 GET 请求 :
http://127.0.0.1:9200/student/_search
{
"_source": ["name","nickname"],
"query": {
"terms": {
"nickname": ["zhangsan"]
}
}
}
3.4.7 过滤字段
includes:来指定想要显示的字段
excludes:来指定不想要显示的字段
请求同上:
{
"_source": {
"includes": ["name","nickname"]
},
"query": {
"terms": {
"nickname": ["zhangsan"]
}
}
}
3.4.8 组合查询
`bool`把各种其它查询通过`must`(必须 )、`must_not`(必须不)、`should`(应该)的方 式进行组合。
3.4.9 范围查询
{
"query": {
"range": {
"age": {
"gte": 30,
"lte": 35
}
}
}
}
3.4.10 模糊查询
返回包含与搜索字词相似的字词的文档。 编辑距离是将一个术语转换为另一个术语所需的一个字符更改的次数。
可用完成的操作:更改字符,删除字符,插入字符,转置两个相邻的字符
{
"query": {
"fuzzy": {
"title": {
"value": "zhangsan",
"fuzziness": 2
}
}
}
}
3.4.11 单字段排序
sort 可以让我们按照不同的字段进行排序,并且通过 order 指定排序的方式。desc 降序,asc 升序。
在 Postman 中,向 ES 服务器发 GET 请求
{
"query": {
"match": {
"name":"zhangsan"
}
},
"sort": [{
"age": {
"order":"desc"
}
}]
}
3.4.12 多字段排序
假定我们想要结合使用 age 和 _score 进行查询,并且匹配的结果首先按照年龄排序,然后 按照相关性得分排序
{
"query": {
"match_all": {}
},
"sort": [
{
"age": {
"order": "desc"
}
},
{
"_score":{
"order": "desc"
}
}
]
}
3.4.13 高亮查询
在进行关键字搜索时,搜索出的内容中的关键字会显示不同的颜色,称之为高亮。
Elasticsearch 可以对查询内容中的关键字部分,进行标签和样式(高亮)的设置。 在使用 match 查询的同时,加上一个 highlight 属性:
pre_tags:前置标签
post_tags:后置标签
fields:需要高亮的字段
title:这里声明 title 字段需要高亮,后面可以为这个字段设置特有配置,也可以空
{
"query": {
"match": {
"name": "zhangsan"
}
},
"highlight": {
"pre_tags": "<font color='red'>",
"post_tags": "</font>",
"fields": {
"name": {}
}
}
}
3.4.14 分页查询
from:当前页的起始索引,默认从 0 开始。 from = (pageNum - 1) * size
size:每页显示多少条
{
"query": {
"match_all": {}
},
"sort": [
{
"age": {
"order": "desc"
}
}
],
"from": 0,
"size": 2
}
3.4.15 聚合查询
聚合允许使用者对 es 文档进行统计分析,类似与关系型数据库中的 group by,当然还有很 多其他的聚合,例如取最大值、平均值等等。
对某个字段取最大值 max
{
"aggs":{
"max_age":{
"max":{"field":"age"}
}
},
"size":0
}
对某个字段取最小值 min
{
"aggs":{
"min_age":{
"min":{"field":"age"}
}
},
"size":0
}
对某个字段求和 sum
{
"aggs":{
"sum_age":{
"sum":{"field":"age"}
}
},
"size":0
}
对某个字段取平均值 avg
{
"aggs":{
"avg_age":{
"avg":{"field":"age"}
}
},
"size":0
}
State 聚合:对某个字段一次性返回 count,max,min,avg 和 sum 五个指标
{
"aggs":{
"stats_age":{
"stats":{"field":"age"}
}
},
"size":0
}
3.4.16 桶聚合查询
桶聚和相当于 sql 中的 group by 语句
terms 聚合,分组统计
{
"aggs":{
"age_groupby":{
"terms":{"field":"age"}
}
},
"size":0
}
4. JavaAPI对Elasticsearch进行访问
4.1 导入依赖
新建maven下面,并将下面的依赖加入到pom.xml文件中
<dependencies>
<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>
</dependencies>
4.2 创建客户端对象
这里我们使用高级REST客户端对象,因为早期版本的客户端对象已经不再使用。
public class Elasticsearch01_Client {
public static void main(String[] args) throws IOException {
RestHighLevelClient EsClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
EsClient.close();
}
}
运行Main(),如果没有报错则说明连接到服务器了。9200 端口为 Elasticsearch 的 Web 通信端口,localhost 为启动 ES 服务的主机名。
4.3 索引操作
4.3.1 创建索引
public class Elasticsearch01_Create_Index {
public static void main(String[] args) throws IOException {
RestHighLevelClient EsClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//创建索引
CreateIndexRequest request = new CreateIndexRequest("user");
CreateIndexResponse createIndexResponse = EsClient.indices().create(request, RequestOptions.DEFAULT);
//响应状态
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println("索引操作"+acknowledged);
EsClient.close();
}
}
结果:
4.3.2 查看索引
public class Elasticsearch01_Find_Index {
public static void main(String[] args) throws IOException {
RestHighLevelClient EsClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询索引
GetIndexRequest get = new GetIndexRequest("user");
GetIndexResponse getIndexResponse = EsClient.indices().get(get, RequestOptions.DEFAULT);
System.out.println(getIndexResponse.getAliases());
System.out.println(getIndexResponse.getMappings());
System.out.println(getIndexResponse.getSettings());
EsClient.close();
}
}
结果:
4.3.3 删除索引
public class Elasticsearch01_Delete_Index {
public static void main(String[] args) throws IOException {
RestHighLevelClient EsClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//删除索引
DeleteIndexRequest request = new DeleteIndexRequest("user");
AcknowledgedResponse delete = EsClient.indices().delete(request, RequestOptions.DEFAULT);
//响应状态
System.out.println(delete.isAcknowledged());
EsClient.close();
}
}
结果:true
4.4 文档操作
4.4.1 新增文档
数据模型:User类,包括三个属性:姓名,性别,年龄
public class User {
private String name;
private String sex;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
新建文档的操作
public class Elasticsearch01_Doc_Insert {
public static void main(String[] args) throws IOException {
RestHighLevelClient EsClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
//插入数据
IndexRequest indexRequest = new IndexRequest();
indexRequest.index("user").id("1001");
User user = new User();
user.setName("张三");
user.setSex("男");
user.setAge(30);
//向ES传入数据需要将数据转换为JSON格式
ObjectMapper mapper = new ObjectMapper();
String userJSON = mapper.writeValueAsString(user);
indexRequest.source(userJSON, XContentType.JSON);
IndexResponse response = EsClient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(response.getResult());
EsClient.close();
}
结果:
4.4.2 修改文档
public class Elasticsearch02_Doc_Update {
public static void main(String[] args) throws IOException {
RestHighLevelClient EsClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
//修改数据
UpdateRequest request = new UpdateRequest();
request.index("user").id("1001");
request.doc(XContentType.JSON,"sex","女");
UpdateResponse update = EsClient.update(request, RequestOptions.DEFAULT);
System.out.println(update);
EsClient.close();
}
}
结果:
4.4.3 查询文档
public class Elasticsearch02_Doc_Get {
public static void main(String[] args) throws IOException {
RestHighLevelClient EsClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
//修改数据
GetRequest request = new GetRequest();
request.index("user").id("1001");
GetResponse get = EsClient.get(request, RequestOptions.DEFAULT);
System.out.println(get.getSourceAsString());
EsClient.close();
}
}
结果:
4.4.4 文档删除
public class Elasticsearch02_Doc_Delete {
public static void main(String[] args) throws IOException {
RestHighLevelClient EsClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
//修改数据
DeleteRequest request = new DeleteRequest();
request.index("user").id("1001");
DeleteResponse response = EsClient.delete(request, RequestOptions.DEFAULT);
System.out.println(response.toString());
EsClient.close();
}
}
结果:
在postman中查询一下:
4.4.5 批量操作
批量插入
public class Elasticsearch02_Doc_Insert_Batch {
public static void main(String[] args) throws IOException {
RestHighLevelClient EsClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
//批量插入数据 简单起见,仅插入名字字段
BulkRequest request = new BulkRequest();
request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON,"name","zhangsan"));
request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON,"name","lisi"));
request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON,"name","wangwu"));
BulkResponse response = EsClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.getTook());
System.out.println(response.getItems());
EsClient.close();
}
}
批量删除
public class Elasticsearch02_Doc_Delete_Batch {
public static void main(String[] args) throws IOException {
RestHighLevelClient EsClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
//批量删除数据 简单起见,仅插入名字字段
BulkRequest request = new BulkRequest();
request.add(new DeleteRequest().index("user").id("1001"));
request.add(new DeleteRequest().index("user").id("1002"));
request.add(new DeleteRequest().index("user").id("1003"));
BulkResponse response = EsClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.getTook());
System.out.println(response.getItems());
EsClient.close();
}
}
4.5 高级查询
向服务器插入数据,代码如下
public class Elasticsearch02_Doc_Insert_Batch {
public static void main(String[] args) throws IOException {
RestHighLevelClient EsClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
//批量插入数据 简单起见,仅插入名字字段
BulkRequest request = new BulkRequest();
request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON,"name","zhangsan","age",30,"sex","男"));
request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON,"name","lisi","age",30,"sex","男"));
request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON,"name","wangwu1","age",30,"sex","男"));
request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON,"name","wangwu2","age",32,"sex","男"));
request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON,"name","wangwu3","age",35,"sex","女"));
request.add(new IndexRequest().index("user").id("1006").source(XContentType.JSON,"name","wangwu4","age",31,"sex","男"));
request.add(new IndexRequest().index("user").id("1007").source(XContentType.JSON,"name","wangwu5","age",20,"sex","女"));
BulkResponse response = EsClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.getTook());
System.out.println(response.getItems());
EsClient.close();
}
}
4.5.1 请求体查询
1) 全量查询
public class Elasticsearch03_Doc_Query {
public static void main(String[] args) throws IOException {
RestHighLevelClient EsClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
//查询数据
SearchRequest request = new SearchRequest();
request.indices("user");
//全量查询,查询索引中所有的数据
request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
SearchResponse response = EsClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(response.getTook());
System.out.println(hits.getTotalHits());
for(SearchHit hit : hits){
System.out.println(hit.getSourceAsString());
}
EsClient.close();
}
}
结果:
2)条件查询
将上面的全量查询语句换成下面条件查询的语句
//2. 条件查询 termQuery()
SearchRequest request = new SearchRequest();
request.indices("user");
//匹配查询的语句
request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age","30")));
SearchResponse response = EsClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(response.getTook());
System.out.println(hits.getTotalHits());
for(SearchHit hit : hits){
System.out.println(hit.getSourceAsString());
}
EsClient.close();
结果:
3) 分页查询
将上面的全量查询语句换成下面条件查询的语句
//3. 分页查询 termQuery() 起始位置和每页查询条数
SearchRequest request = new SearchRequest();
request.indices("user");
//匹配查询的语句
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//每页的起始号码 = (当前页码-1)*每页显示的数据条数
//起始索引
builder.from(0);
//每页显示多少条数据
builder.size(2);
request.source(builder);
SearchResponse response = EsClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(response.getTook());
System.out.println(hits.getTotalHits());
for(SearchHit hit : hits){
System.out.println(hit.getSourceAsString());
}
结果:
4)排序查询
//4. 数据排序
SearchRequest request = new SearchRequest();
request.indices("user");
//匹配查询的语句
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//排序的字段和排序的方式
builder.sort("age", SortOrder.DESC);
request.source(builder);
SearchResponse response = EsClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(response.getTook());
System.out.println(hits.getTotalHits());
for(SearchHit hit : hits){
System.out.println(hit.getSourceAsString());
}
结果:
5)过滤字段查询
//5. 过滤字段查询
SearchRequest request = new SearchRequest();
request.indices("user");
//匹配查询的语句
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//排除数组,包含数组
String[] includes = {"name"};
String[] excludes = {};
builder.fetchSource(includes,excludes);
request.source(builder);
SearchResponse response = EsClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(response.getTook());
System.out.println(hits.getTotalHits());
for(SearchHit hit : hits){
System.out.println(hit.getSourceAsString());
}
结果:
6) 组合条件查询 BoolQuery
//6. 组合条件查询
SearchRequest request = new SearchRequest();
request.indices("user");
//匹配查询的语句
SearchSourceBuilder builder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(QueryBuilders.matchQuery("age",30));
boolQueryBuilder.must(QueryBuilders.matchQuery("sex","男"));
builder.query(boolQueryBuilder);
request.source(builder);
SearchResponse response = EsClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(response.getTook());
System.out.println(hits.getTotalHits());
for(SearchHit hit : hits){
System.out.println(hit.getSourceAsString());
}
结果:
7)范围查询
//7. 范围查询
SearchRequest request = new SearchRequest();
request.indices("user");
//匹配查询的语句
SearchSourceBuilder builder = new SearchSourceBuilder();
RangeQueryBuilder query = QueryBuilders.rangeQuery("age");
//年龄大于等于30,小于等于40
query.gte(30);
query.lte(40);
builder.query(query);
request.source(builder);
SearchResponse response = EsClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(response.getTook());
System.out.println(hits.getTotalHits());
for(SearchHit hit : hits){
System.out.println(hit.getSourceAsString());
}
结果:
8)模糊查询
//8. 模糊查询——根据其中的一部分进行模糊匹配
SearchRequest request = new SearchRequest();
request.indices("user");
//匹配查询的语句
SearchSourceBuilder builder = new SearchSourceBuilder();
//模糊查询 字符相差为一个的
FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("name", "wangwu").fuzziness(Fuzziness.ONE);
builder.query(fuzzyQueryBuilder);
request.source(builder);
SearchResponse response = EsClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(response.getTook());
System.out.println(hits.getTotalHits());
for(SearchHit hit : hits){
System.out.println(hit.getSourceAsString());
}
结果:
4.5.2 高亮查询
//8. 高亮查询
SearchRequest request = new SearchRequest();
request.indices("user");
//匹配查询的语句
SearchSourceBuilder builder = new SearchSourceBuilder();
TermQueryBuilder query = QueryBuilders.termQuery("name", "zhangsan");
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("<font color='red'>");
highlightBuilder.postTags("</font>");
highlightBuilder.field("name");
builder.highlighter(highlightBuilder);
builder.query(query);
request.source(builder);
SearchResponse response = EsClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(response.getTook());
System.out.println(hits.getTotalHits());
for(SearchHit hit : hits){
System.out.println(hit.getSourceAsString());
}
结果:
4.5.3 聚合查询
最大值年龄查询
//8. 最大查询
SearchRequest request = new SearchRequest();
request.indices("user");
//匹配查询的语句
SearchSourceBuilder builder = new SearchSourceBuilder();
AggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");
builder.aggregation(aggregationBuilder);
request.source(builder);
SearchResponse response = EsClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(response.getTook());
System.out.println(hits.getTotalHits());
for(SearchHit hit : hits){
System.out.println(hit.getSourceAsString());
}
分组查询
SearchRequest request = new SearchRequest();
request.indices("user");
//匹配查询的语句
SearchSourceBuilder builder = new SearchSourceBuilder();
AggregationBuilder aggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");
builder.aggregation(aggregationBuilder);
request.source(builder);
SearchResponse response = EsClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(response.getTook());
System.out.println(hits.getTotalHits());
for(SearchHit hit : hits){
System.out.println(hit.getSourceAsString());
}