Java API

IDEA中创建一个Maven项目;

pom中添加依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<dependencies>
<!-- lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>

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

测试运行:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;

public class App {
public static void main(String[] args) {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

// 关闭es客户端
try {
esclient.close();
System.out.println("运行结束");
} catch (IOException e) {
e.printStackTrace();
}

}
}

测试运行,没有报错信息,正常结束,即为运行成功

控制台输出:

1
运行结束

图片

索引操作

创建索引

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;

import java.io.IOException;

public class IndexCreate {
public static void main(String[] args) throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
// 构建请求对,索引名称为user
CreateIndexRequest request = new CreateIndexRequest("user");
//indices():拿到索引,create()创建,需要处理异常
CreateIndexResponse createIndexResponse = esclient.indices().create(request, RequestOptions.DEFAULT);
// 获取响应状态
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println("索引操作:" + acknowledged);
// 关闭es客户端
try {
esclient.close();
System.out.println("运行结束");
} catch (IOException e) {
e.printStackTrace();
}

}
}

控制台输出:

1
2
索引操作:true
运行结束

图片

查看索引

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;

import java.io.IOException;

public class IndexSearch {
public static void main(String[] args) throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
// 构建请求对,索引名称为user
GetIndexRequest indexRequest = new GetIndexRequest("user");
//indices():拿到索引
GetIndexResponse indexResponse = esclient.indices().get(indexRequest,RequestOptions.DEFAULT);
// 获取别名
System.out.println(indexResponse.getAliases());
// 获取映射
System.out.println(indexResponse.getMappings());
// 获取配置
System.out.println(indexResponse.getSettings());
// 关闭es客户端
try {
esclient.close();
System.out.println("运行结束");
} catch (IOException e) {
e.printStackTrace();
}

}
}

控制台输出:

1
2
3
4
{user=[]}
{user=org.elasticsearch.cluster.metadata.MappingMetadata@eb05fb5f}
{user={"index.creation_date":"1633605284327","index.number_of_replicas":"1","index.number_of_shards":"1","index.provided_name":"user","index.routing.allocation.include._tier_preference":"data_content","index.uuid":"YNoEXLS8TKuUhONVK2dkuQ","index.version.created":"7150099"}}
运行结束

图片

删除索引

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;

public class IndexDelete {
public static void main(String[] args) throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
// 构建请求对,索引名称为user
DeleteIndexRequest indexRequest = new DeleteIndexRequest("user");
//indices():拿到索引
AcknowledgedResponse indexResponse = esclient.indices().delete(indexRequest, RequestOptions.DEFAULT);
// 获取响应状态
System.out.println(indexResponse.isAcknowledged());
// 关闭es客户端
try {
esclient.close();
System.out.println("运行结束");
} catch (IOException e) {
e.printStackTrace();
}

}
}

控制台输出

1
2
true
运行结束

文档操作

实体类:

1
2
3
4
5
6
7
8
9
10
11
12
13
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private String nickName;
private String sex;
private Integer age;
}

创建文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class ESDoc {
public static void main(String[] args) throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

// 创建请求对象
IndexRequest indexRequest = new IndexRequest();

indexRequest.index("user").id("1001");
User user = new User("张三","zhangsan","man",18);
// 将对象转为Json类型
ObjectMapper objectMapper = new ObjectMapper();
String jsonValue = objectMapper.writeValueAsString(user);

// 将json类型对象放在请求体中
indexRequest.source(jsonValue, XContentType.JSON);

// 插入数据
IndexResponse indexResponse = esclient.index(indexRequest, RequestOptions.DEFAULT);

System.out.println(indexResponse.getResult());


// 关闭es客户端
try {
esclient.close();
System.out.println("运行结束");
} catch (IOException e) {
e.printStackTrace();
}

}
}

控制台输出:

1
2
CREATED
运行结束

修改文档

局部更新

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import org.apache.http.HttpHost;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class UpdateDoc {

public static void main(String[] args) throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

// 创建更新请求对象
UpdateRequest request = new UpdateRequest();

request.index("user").id("1001");

// 设置要修改的数据
request.doc(XContentType.JSON, "age", 21);

// 进行修改数据操作
UpdateResponse response = esclient.update(request, RequestOptions.DEFAULT);

System.out.println(response.getResult());

// 关闭es客户端
try {
esclient.close();
System.out.println("运行结束");
} catch (IOException e) {
e.printStackTrace();
}

}
}

控制台输出:

1
2
UPDATED
运行结束

查询文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;

public class SearchDoc {
public static void main(String[] args) throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

// 创建请求对象
GetRequest request = new GetRequest();
request.index("user").id("1001");

// 查询数据
GetResponse response = esclient.get(request, RequestOptions.DEFAULT);
System.out.println(response.getSourceAsString());

// 关闭es客户端
try {
esclient.close();
System.out.println("运行结束");
} catch (IOException e) {
e.printStackTrace();
}
}
}

控制台输出:

1
2
UPDATED
运行结束

删除文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;

public class DeleteDoc {
public static void main(String[] args) throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
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.getResult());

// 关闭es客户端
try {
esclient.close();
System.out.println("运行结束");
} catch (IOException e) {
e.printStackTrace();
}
}
}

控制台输出:

1
2
DELETED
运行结束

批量操作

  • 批量插入数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class BulkDoc {
public static void main(String[] args) throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

// 创建批量请求对象
BulkRequest request = new BulkRequest();

// 添加数据(这里没有使用实体类对象,而是直接插入一个简单的Json数据)
request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON,"name","李四"));
request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON,"name","王五"));

// 进行批量操作
BulkResponse response = esclient.bulk(request, RequestOptions.DEFAULT);
// 获取消耗时间
System.out.println(response.getTook());

System.out.println(response.getItems());

// 关闭es客户端
try {
esclient.close();
System.out.println("运行结束");
} catch (IOException e) {
e.printStackTrace();
}
}
}

控制台输出:

1
2
3
6ms
[Lorg.elasticsearch.action.bulk.BulkItemResponse;@3e27ba32
运行结束
  • 批量删除数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;

public class BulkDeleteDoc {
public static void main(String[] args) throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

// 创建批量请求对象
BulkRequest request = new BulkRequest();
// 创建删除请求
DeleteRequest deleteRequest = new DeleteRequest();
// 添加需要删除的文档
request.add(deleteRequest.index("user").id("1002"));
request.add(deleteRequest.index("user").id("1003"));

// 进行批量操作
BulkResponse response = esclient.bulk(request, RequestOptions.DEFAULT);
// 获取消耗时间
System.out.println(response.getTook());

System.out.println(response.getItems());

// 关闭es客户端
try {
esclient.close();
System.out.println("运行结束");
} catch (IOException e) {
e.printStackTrace();
}
}
}

控制台输出:

1
2
3
5ms
[Lorg.elasticsearch.action.bulk.BulkItemResponse;@1ed6388a
运行结束

高级查询

一些常用的高级查询,在【HTTP操作】的高级查询中已经写的比较详细了,所以【Java API】里面就对详略进行了一些区分,略写的部分可以参考【HTTP操作】部分结合【Java API】中的高级查询详写的部分;

后续有时间的话也会对略写部分进行补充

首先创建查询需要的数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class BulkDoc {
public static void main(String[] args) throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

// 创建批量请求对象
BulkRequest request = new BulkRequest();


// 添加数据(这里没有使用实体类对象,而是直接插入一个简单的Json数据)
request.add(new IndexRequest().index("phone").id("1001").source(XContentType.JSON,"name","小米手机","price","3999","content","MIUI Based on Android OS","area","China"));
request.add(new IndexRequest().index("phone").id("1002").source(XContentType.JSON,"name","小米手机","price","4299","content","MIUI Based on Android OS","area","China"));
request.add(new IndexRequest().index("phone").id("1003").source(XContentType.JSON,"name","华为手机","price","4488","content","HarmonyOS Based on Harmony OS","area","China"));
request.add(new IndexRequest().index("phone").id("1004").source(XContentType.JSON,"name","华为手机Pro","price","6488","content","HarmonyOS Not based on Android OS","area","China"));
request.add(new IndexRequest().index("phone").id("1005").source(XContentType.JSON,"name","苹果手机","price","5199","content","IOS Not based on Android OS","area","American"));
request.add(new IndexRequest().index("phone").id("1006").source(XContentType.JSON,"name","苹果手机Pro","price","7999","content","IOS Not based on Harmony OS","area","American"));

// 进行批量操作

BulkResponse response = esclient.bulk(request, RequestOptions.DEFAULT);
// 获取消耗时间
System.out.println(response.getTook());

System.out.println(response.getItems());

// 关闭es客户端
try {
esclient.close();
System.out.println("运行结束");
} catch (IOException e) {
e.printStackTrace();
}
}
}

全量查询【matchAllQuery()】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;

import java.io.IOException;


public class QueryDoc {

@Test
public void queryTest() throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

// 创建请求对象
SearchRequest request = new SearchRequest();
// 指定目标索引
request.indices("phone");
// 设置请求体内容(构建查询对象,同时调用全量查询方法)
SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
// 放入请求体
request.source(query);

// 执行查询操作
SearchResponse response = esclient.search(request, RequestOptions.DEFAULT);

// 打印查询到的数量
System.out.println(response.getHits().getTotalHits());

// 打印查询的数据
for(SearchHit hit: response.getHits()){
System.out.println(hit.getSourceAsString());
}

// 关闭es
esclient.close();
}

}

控制台输出:

1
2
3
4
5
6
7
6 hits
{"name":"小米手机","price":"3999","content":"MIUI Based on Android OS","area":"China"}
{"name":"小米手机","price":"4299","content":"MIUI Based on Android OS","area":"China"}
{"name":"华为手机","price":"4488","content":"HarmonyOS Based on Harmony OS","area":"China"}
{"name":"华为手机Pro","price":"6488","content":"HarmonyOS Not based on Android OS","area":"China"}
{"name":"苹果手机","price":"5199","content":"IOS Not based on Android OS","area":"American"}
{"name":"苹果手机Pro","price":"7999","content":"IOS Not based on Harmony OS","area":"American"}

匹配查询【matchQuery()】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;

import java.io.IOException;


public class QueryDoc {

@Test
public void queryTest2() throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

// 创建请求对象
SearchRequest request = new SearchRequest();
// 指定目标索引
request.indices("phone");
// 设置请求体内容(构建查询对象,同时调用查询方法)
SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchQuery("name","华为"));
// 放入请求体
request.source(query);

// 执行查询操作
SearchResponse response = esclient.search(request, RequestOptions.DEFAULT);

// 打印查询到的数量
System.out.println(response.getHits().getTotalHits());

// 打印查询的数据
for(SearchHit hit: response.getHits()){
System.out.println(hit.getSourceAsString());
}

// 关闭es
esclient.close();
}
}

控制台输出:

1
2
3
2 hits
{"name":"华为手机","price":"4488","content":"HarmonyOS Based on Harmony OS","area":"China"}
{"name":"华为手机Pro","price":"6488","content":"HarmonyOS Not based on Android OS","area":"China"}

字段匹配查询【multiMatchQuery()】

可参考前面部分及【HTTP操作】中对应的部分

关键字精确查询【termQuery()】

可参考前面部分及【HTTP操作】中对应的部分

多关键字精确查询【termsQuery()】

可参考前面部分及【HTTP操作】中对应的部分

过滤字段(fetchSource)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;

import java.io.IOException;


public class QueryDoc {
@Test
public void fetchTest() throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

// 创建请求对象
SearchRequest request = new SearchRequest();
// 指定目标索引
request.indices("phone");
// 构建查询对象
SearchSourceBuilder searchQuery = new SearchSourceBuilder();
// 设置请求体
searchQuery.query(QueryBuilders.matchQuery("name","华为"));
// 设置查询结果中要过滤的字段
String[] excludes = {"content","area"}; //指定不想要的字段
String[] includes = {}; //指定想要的字段 (因为已经指定不想要的字段了,所以除了不想要的字段,其它字段都会显示出来,所以这里也就可以省略)
searchQuery.fetchSource(includes,excludes);

// 放入请求体
request.source(searchQuery);

// 执行查询操作
SearchResponse response = esclient.search(request, RequestOptions.DEFAULT);

// 打印查询到的数量
System.out.println(response.getHits().getTotalHits());

// 打印查询的数据
for(SearchHit hit: response.getHits()){
System.out.println(hit.getSourceAsString());
}

// 关闭es
esclient.close();
}
}

控制台输出:

1
2
3
2 hits
{"price":"4488","name":"华为手机"}
{"price":"6488","name":"华为手机Pro"}

组合查询【boolQuery()】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;

import java.io.IOException;


public class QueryDoc {
@Test
public void boolTest() throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

// 创建请求对象
SearchRequest request = new SearchRequest();
// 指定目标索引
request.indices("phone");
// 构建查询对象
SearchSourceBuilder searchQuery = new SearchSourceBuilder();

// 设置请求体
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(QueryBuilders.matchQuery("area","China"));
boolQueryBuilder.mustNot(QueryBuilders.matchQuery("content","abc"));
boolQueryBuilder.should(QueryBuilders.matchQuery("name","华为"));

searchQuery.query(boolQueryBuilder);

// 放入请求体
request.source(searchQuery);

// 执行查询操作
SearchResponse response = esclient.search(request, RequestOptions.DEFAULT);

// 打印查询到的数量
System.out.println(response.getHits().getTotalHits());

// 打印查询的数据
for(SearchHit hit: response.getHits()){
System.out.println(hit.getSourceAsString());
}

// 关闭es
esclient.close();
}
}

控制台输出:

1
2
3
4
5
4 hits
{"name":"华为手机","price":"4488","content":"HarmonyOS Based on Harmony OS","area":"China"}
{"name":"华为手机Pro","price":"6488","content":"HarmonyOS Not based on Android OS","area":"China"}
{"name":"小米手机","price":"3999","content":"MIUI Based on Android OS","area":"China"}
{"name":"小米手机","price":"4299","content":"MIUI Based on Android OS","area":"China"}

范围查询【rangeQuery()】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;

import java.io.IOException;


public class QueryDoc {
@Test
public void rangeTest() throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

// 创建请求对象
SearchRequest request = new SearchRequest();
// 指定目标索引
request.indices("phone");
// 构建查询对象
SearchSourceBuilder searchQuery = new SearchSourceBuilder();

// 设置请求体
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("price");

rangeQuery.gte("3000");// 大于等于
rangeQuery.lte("4500");// 小于等于

searchQuery.query(rangeQuery);

// 放入请求体
request.source(searchQuery);

// 执行查询操作
SearchResponse response = esclient.search(request, RequestOptions.DEFAULT);

// 打印查询到的数量
System.out.println(response.getHits().getTotalHits());

// 打印查询的数据
for(SearchHit hit: response.getHits()){
System.out.println(hit.getSourceAsString());
}

// 关闭es
esclient.close();
}
}
1
2
3
4
3 hits
{"name":"小米手机","price":"3999","content":"MIUI Based on Android OS","area":"China"}
{"name":"小米手机","price":"4299","content":"MIUI Based on Android OS","area":"China"}
{"name":"华为手机","price":"4488","content":"HarmonyOS Based on Harmony OS","area":"China"}

模糊查询

待补充

高亮查询【highlighter()】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.junit.Test;

import java.io.IOException;
import java.util.Map;


public class QueryDoc {
@Test
public void highlightTest() throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

// 创建请求对象
SearchRequest request = new SearchRequest();
// 指定目标索引
request.indices("phone");
// 构建查询对象
SearchSourceBuilder searchQuery = new SearchSourceBuilder();

// 设置请求体(查询方式)
MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("name","小米");
searchQuery.query(queryBuilder);

// 构建高亮字段
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("<font color='red'");//设置标签前缀 (可不设,不设默认为<em>)
highlightBuilder.postTags("</font>");//设置标签后缀(可不设,不设默认为</em>)
highlightBuilder.field("name");//设置需要高亮的字段
// 设置高亮构建对象
searchQuery.highlighter(highlightBuilder);

// 放入请求体
request.source(searchQuery);

// 执行查询操作
SearchResponse response = esclient.search(request, RequestOptions.DEFAULT);

// 打印结果
SearchHits hits = response.getHits();
System.out.println("took:"+response.getTook());
System.out.println("time_out:"+response.isTimedOut());
System.out.println("total:"+hits.getTotalHits());
System.out.println("max_score:"+hits.getMaxScore());
System.out.println("hits:{");

// 打印查询的数据
for(SearchHit hit: response.getHits()){
System.out.println(hit.getSourceAsString());
//打印高亮结果
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
System.out.println(highlightFields);
}
System.out.println("}");
// 关闭es
esclient.close();
}
}

控制台输出:

1
2
3
4
5
6
7
8
9
10
took:1ms
time_out:false
total:2 hits
max_score:2.1261456
hits:{
{"name":"小米手机","price":"3999","content":"MIUI Based on Android OS","area":"China"}
{name=[name], fragments[[<font color='red'小</font><font color='red'米</font>手机]]}
{"name":"小米手机","price":"4299","content":"MIUI Based on Android OS","area":"China"}
{name=[name], fragments[[<font color='red'小</font><font color='red'米</font>手机]]}
}

排序查询【sort】

待补充

分页查询【from】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;

import java.io.IOException;
import java.util.Map;


public class QueryDoc {
@Test
public void formTest() throws IOException {
// 创建ES客户端(采用高级 REST 客户端对象访问)
RestHighLevelClient esclient = new RestHighLevelClient(
//访问地址:new HttpHost("ip",端口,"访问方式")
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

// 创建请求对象
SearchRequest request = new SearchRequest();

// 指定目标索引
request.indices("phone");

// 构建查询对象
SearchSourceBuilder searchQuery = new SearchSourceBuilder();

// 设置请求体(查询方式)
MatchAllQueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
searchQuery.query(queryBuilder);
// 分页查询
searchQuery.from(0);
searchQuery.size(3);

// 放入请求体
request.source(searchQuery);

// 执行查询操作
SearchResponse response = esclient.search(request, RequestOptions.DEFAULT);

// 打印结果
SearchHits hits = response.getHits();
System.out.println("took:"+response.getTook());
System.out.println("time_out:"+response.isTimedOut());
System.out.println("total:"+hits.getTotalHits());
System.out.println("max_score:"+hits.getMaxScore());
System.out.println("hits:{");

// 打印查询的数据
for(SearchHit hit: response.getHits()){
System.out.println(hit.getSourceAsString());
}
System.out.println("}");
// 关闭es
esclient.close();
}
}

控制台输出:

1
2
3
4
5
6
7
8
9
took:2ms
time_out:false
total:6 hits
max_score:1.0
hits:{
{"name":"小米手机","price":"3999","content":"MIUI Based on Android OS","area":"China"}
{"name":"小米手机","price":"4299","content":"MIUI Based on Android OS","area":"China"}
{"name":"华为手机","price":"4488","content":"HarmonyOS Based on Harmony OS","area":"China"}
}

聚合查询【aggregation()】

度量查询

包括最大值(max)、最小值(min)、平均值(avg)、求和(sum)、总数(count)、 去重后求总数(cardinality)、返回所有度量类型的统计(stats)等等。

桶聚合查询

在已有的分组条件下再进行聚合即为桶聚合,相当于MySQL中的group by 语句;桶聚合返回很多子集,并限定输入数据到一个特殊的叫做桶的子集中。可以把桶聚合想象成类似切面功能的东西。

  • term聚合:词条的聚合

    terms聚合为字段中每个词条返回一个桶。允许你生成字段每个值的统计;

  • range聚合和date range聚合

    范围聚合和时间范围聚合

  • 桶嵌套

    多个聚合的嵌套即为桶嵌套