目录

ElasticSearch - Java操作

# 项目准备

Elasticsearch 软件是由 Java 语言开发的,所以也可以通过 Java API 的方式对 Elasticsearch 服务进行访问

# 项目配置

pom.xml

<dependencies>
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>7.15.2</version>
    </dependency>
    <!-- elasticsearch 的客户端 -->
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>7.15.2</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.3</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
24
25
26
27
28
29
30
31
32
33
34
35

elasticsearch 的两个依赖要和 elasticsearch 服务器版本一致。

# 客户端对象

建好项目,创建一个类,测试连接 ES 服务器

package com.kbt;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;

/**
 * @author Young Kbt
 * @date 2021/11/15 15:15
 * @description ElasticSearch 客户端
 */
public class EsTestClient {

    public static void main(String[] args) throws IOException {
        // 连接 ES 客户端 
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http")));
        // 关闭 ES 客户端
        esClient.close();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

运行后控制台如果不报错,则代表连接成功。

注意:9200 端口为 Elasticsearch 的 Web 通信端口,localhost 为启动 ES 服务的主机名。

# 索引操作

ES 服务器正常启动后,可以通过 Java API 客户端对象对 ES 索引进行操作

# 创建索引

需要 CreateIndexRequest 类进行创建索引,通过 indices().create() 发送到服务器进行创建

package com.kbt.index;

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;

/**
 * @author Young Kbt
 * @date 2021/11/15 16:38
 * @description ES 索引的创建
 */
public class EsIndexCreate {

    public static void main(String[] args) throws IOException {

        // 连接 ES 客户端 
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http")));
       
        // 创建索引的请求对象
        CreateIndexRequest request = new CreateIndexRequest("user");
        // 第二个参数默认请求即可
        CreateIndexResponse responsejava = esClient.indices().create(request, RequestOptions.DEFAULT);
        boolean acknowledged = response.isAcknowledged();
        System.out.println("创建索引状态:" + acknowledged);
		// 关闭 ES 客户端
        esClient.close();

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

返回 true,代表创建索引成功

另一种创建方法是:

public class EsDocUpdate {

    public static void main(String[] args) throws IOException {
        // 连接 ES 客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http")));

        IndexRequest request = new IndexRequest();
        request.index("user").id("1001");
        // 客户端发送请求,获取响应对象
        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
        System.out.println("创建的索引:" + response.getIndex());
        System.out.println("创建的 id:" + response.getId());
        System.out.println("创建的结果:" + response.getResult());

        // 关闭 ES 客户端
        esClient.close();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 查看索引

package com.kbt.index;

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 org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;

import java.io.IOException;

/**
 * @author Young Kbt
 * @date 2021/11/15 16:38
 * @description ES 索引的查询
 */
public class EsIndexQuery {

    public static void main(String[] args) throws IOException {

        // 连接 ES 客户端 
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http")));
        
        // 创建索引的请求对象
        GetIndexRequest request = new GetIndexRequest("user");
        GetIndexResponse response = esClient.indices().get(request, RequestOptions.DEFAULT);
        
        System.out.println("索引别名:" + response.getAliases());
        System.out.println("索引映射:" + response.getMappings());
        System.out.println("索引配置:" + response.getSettings());
        // 关闭 ES 客户端
        esClient.close();

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

返回结果:

image-20211115170150991

# 删除索引

package com.kbt.index;

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 org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;

import java.io.IOException;

/**
 * @author Young Kbt
 * @date 2021/11/15 16:38
 * @description ES 索引的删除
 */
public class EsIndexDelete {

    public static void main(String[] args) throws IOException {

        // 连接 ES 客户端 
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http")));
        
        // 创建索引的请求对象
        DeleteIndexRequest request = new DeleteIndexRequest("user");
        AcknowledgedResponse response = esClient.indices().delete(request, RequestOptions.DEFAULT);
        
        System.out.println("删除状态:" + response.isAcknowledged());
        // 关闭 ES 客户端
        esClient.close();
    }
}
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

返回结果:

image-20211115170634402

# 总结

关于索引的请求,用到 xxxIndexRequest 以及 .indices().xxx,其中 xxx 代表增删查,

# 文档操作

# 新增文档

首先需要创建一个实体类:User

package com.kbt.pojo;

/**
 * @author Young Kbt
 * @date 2021/11/15 17:13
 * @description 用户实体类
 */
public class User {
    /**
     * 用户名
     */
    private String username;
    /**
     * 年龄
     */
    private int age;
    /**
     * 性别
     */
    private String sex;

    public User(String username, int age, String sex) {
        this.username = username;
        this.age = age;
        this.sex = sex;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}
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

创建数据,添加到文档中

package com.kbt.doc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kbt.pojo.User;
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;

/**
 * @author Young Kbt
 * @date 2021/11/15 17:16
 * @description ES 文档的创建
 */
public class EsDocCreate {

    public static void main(String[] args) throws IOException {
        // 连接 ES 客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http")));

        IndexRequest request = new IndexRequest();
        request.index("user").id("1001");
        // 创建数据对象
        User user = new User("可乐",18,"男");
        // 数据转换为 Json 字符串格式
        ObjectMapper objectMapper = new ObjectMapper();
        String userJsonStr = objectMapper.writeValueAsString(user);
        // 添加文档数据,数据格式为 Json 格式
        request.source(userJsonStr, XContentType.JSON);
        // 客户端发送请求,获取响应对象
        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
        System.out.println("创建的索引:" + response.getIndex());
        System.out.println("创建的 id:" + response.getId());
        System.out.println("创建的结果:" + response.getResult());

        // 关闭 ES 客户端
        esClient.close();
    }
}
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

结果:

image-20211115174732343

笔记

你会发现,响应对象的方法里,使用 getXXX 获取某些数据中,XXX 就是之前 Postman 返回结果的 Key 名

# 修改文档













 
 
 
 
 
 











/**
 * @author Young Kbt
 * @date 2021/11/15 17:16
 * @description ES 文档的修改
 */
public class EsDocUpdate {

    public static void main(String[] args) throws IOException {
        // 连接 ES 客户端
        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 response = esClient.update(request, RequestOptions.DEFAULT);
        System.out.println("创建的索引:" + response.getIndex());
        System.out.println("创建的 id:" + response.getId());
        System.out.println("修改的结果:" + response.getResult());


        // 关闭 ES 客户端
        esClient.close();
    }
}
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

返回结果:

image-20211115180819049

# 查询文档














 
 

 









15/**
 * @author Young Kbt
 * @date 2021/11/15 17:16
 * @description ES 文档的创建
 */
public class EsDocQuery {

    public static void main(String[] args) throws IOException {
        // 连接 ES 客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                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.getIndex());
        System.out.println("创建的 id:" + response.getId());
        System.out.println("查询的结果:" + response.getSourceAsString());

        // 关闭 ES 客户端
        esClient.close();
    }
}
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

返回的结果:

image-20211115180721581

# 删除文档













 

 

 







/**
 * @author Young Kbt
 * @date 2021/11/15 17:16
 * @description ES 文档的删除
 */
public class EsDocDelete {

    public static void main(String[] args) throws IOException {
        // 连接 ES 客户端
        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());

        // 关闭 ES 客户端
        esClient.close();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

返回结果:

image-20211115181039326

# 批量新增

    public class EsDocCreateBatch {
    
      public static void main(String[] args) throws IOException {
          // 连接 ES 客户端
          RestHighLevelClient esClient = new RestHighLevelClient(
              RestClient.builder(new HttpHost("localhost",9200,"http")));
    
          BulkRequest request = new BulkRequest();
          ObjectMapper objectMapper = new ObjectMapper();
          // 创建数据对象
          request.add(new IndexRequest().index("user").id("1001").source(objectMapper.writeValueAsString(new User("可乐", 18, "男")), XContentType.JSON));
          request.add(new IndexRequest().index("user").id("1002").source(objectMapper.writeValueAsString(new User("冰糖", 20, "女")), XContentType.JSON));
          request.add(new IndexRequest().index("user").id("1003").source(objectMapper.writeValueAsString(new User("雪梨", 22, "女")), XContentType.JSON));
          request.add(new IndexRequest().index("user").id("1004").source(objectMapper.writeValueAsString(new User("酸橙", 24, "男")), XContentType.JSON));
          request.add(new IndexRequest().index("user").id("1005").source(objectMapper.writeValueAsString(new User("蜜桃", 30, "女")), XContentType.JSON));
          // 客户端发送请求,获取响应对象
          BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
          System.out.println("响应时间:" + response.getTook());
          System.out.println("创建的内容:" + Arrays.toString(response.getItems()));
    
          // 关闭 ES 客户端
          esClient.close();
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    public class EsDocCreateBatch {
    
        public static void main(String[] args) throws IOException {
            // 连接 ES 客户端
            RestHighLevelClient esClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http")));
    
            BulkRequest request = new BulkRequest();
            // 创建数据对象
            User user = new User("可乐","18","男");
            request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "username","可乐","age",18,"sex","男"));
            request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "username","冰糖","age",20,"sex","女"));
            request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "username","雪梨","age",22,"sex","女"));
            request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "username","酸橙","age",24,"sex","男"));
            request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "username","蜜桃","age",26,"sex","女"));
            // 客户端发送请求,获取响应对象
            BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
            System.out.println("响应时间:" + response.getTook());
            System.out.println("创建的内容:" + Arrays.toString(response.getItems()));
    
    
            // 关闭 ES 客户端
            esClient.close();
        }
    }
    
    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
    // Make sure to add code blocks to your code group

    返回结果:

    image-20211115182932649

    创建内容无法打印完整的数据,只能打印数据的地址。

    # 批量删除

    public class EsDocDeleteBatch {
    
        public static void main(String[] args) throws IOException {
            // 连接 ES 客户端
            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"));
            request.add(new DeleteRequest().index("user").id("1004"));
            request.add(new DeleteRequest().index("user").id("1005"));
            // 客户端发送请求,获取响应对象
            BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
            //打印结果信息
            System.out.println("响应时间:" + response.getTook());
    
            // 关闭 ES 客户端
            esClient.close();
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23

    image-20211115183705983

    # 总结

    增删改查操作格式:

    • 连接 ES 客户端
    • 创建一个 XXXRequest 对象,其中 XXX 代表增删改查
    • 给该对象设置索引和文档
    • 调用 .XXX请求,传入参数,其中 XXX 代表增删改查

    # 高级查询

    # 查询准备

    本内容都是查询相关,所以需要插入几条数据

    public class EsDocCreateBatch {
    
        public static void main(String[] args) throws IOException {
            // 连接 ES 客户端
            RestHighLevelClient esClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http")));
    
            BulkRequest request = new BulkRequest();
            ObjectMapper objectMapper = new ObjectMapper();
            // 创建数据对象
            request.add(new IndexRequest().index("user").id("1001").source(objectMapper.writeValueAsString(new User("可乐", 18, "男")), XContentType.JSON));
            request.add(new IndexRequest().index("user").id("1002").source(objectMapper.writeValueAsString(new User("冰糖", 20, "女")), XContentType.JSON));
            request.add(new IndexRequest().index("user").id("1003").source(objectMapper.writeValueAsString(new User("雪梨", 22, "女")), XContentType.JSON));
            request.add(new IndexRequest().index("user").id("1004").source(objectMapper.writeValueAsString(new User("酸橙", 24, "男")), XContentType.JSON));
            request.add(new IndexRequest().index("user").id("1005").source(objectMapper.writeValueAsString(new User("蜜桃", 30, "女")), XContentType.JSON));
            // 客户端发送请求,获取响应对象
            BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
            System.out.println("响应时间:" + response.getTook());
    
            // 关闭 ES 客户端
            esClient.close();
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23

    image-20211115183824053

    # 查询所有索引数据














     


















    public class EsQueryAll {
        
        public static void main(String[] args) throws IOException {
            // 连接 ES 客户端 
            RestHighLevelClient esClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http")));
    
            // 创建搜索请求对象
            SearchRequest request = new SearchRequest();
            request.indices("user");
            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            // 查询所有数据
            sourceBuilder.query(QueryBuilders.matchAllQuery());
            SearchResponse response = esClient.search(request.source(sourceBuilder), RequestOptions.DEFAULT);
            // 查询匹配
            SearchHits hits = response.getHits();
            System.out.println("响应时间:" + response.getTook());
            System.out.println("是否超时:" + response.isTimedOut());
            System.out.println("命中数量:" + hits.getTotalHits());
            System.out.println("MaxScore:" + hits.getMaxScore());
            System.out.println("详细数据:");
            for (SearchHit hit : hits) {
                // 输出每条查询的结果信息
                System.out.println(hit.getSourceAsString());
            }
    
            // 关闭java ES 客户端
            esClient.close();
        }
    }
    
    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

    indices(参数) 的参数可以是多个索引。

    返回结果:

    image-20211115191241326

    # term查询

    查询某个字段,查询条件为关键字,如果查询分词,则会报错,在问题查看













     


















    public class EsTermQuery {
    
        public static void main(String[] args) throws IOException {
            // 连接 ES 客户端 
            RestHighLevelClient esClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http")));
    
            SearchRequest request = new SearchRequest();
            request.indices("user");
            
            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(QueryBuilders.termQuery("age", "18"));
            SearchResponse response = esClient.search(request.source(sourceBuilder), RequestOptions.DEFAULT);
            // 查询匹配
            SearchHits hits = response.getHits();
            System.out.println("响应时间:" + response.getTook());
            System.out.println("是否超时:" + response.isTimedOut());
            System.out.println("命中数量:" + hits.getTotalHits());
            System.out.println("MaxScore:" + hits.getMaxScore());
            System.out.println("详细数据:");
            for (SearchHit hit : hits) {
                // 输出每条查询的结果信息
                System.out.println(hit.getSourceAsString());
            }
    
            // 关闭 ES 客户端
            esClient.close();
        }
    } sourceBuilder.query(QueryBuilders.termsQuery("age", "18","20","22"));
    
    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

    返回结果:

    image-20211115191259760

    # terms查询













     


















    public class EsTermQuery {
    
        public static void main(String[] args) throws IOException {
            // 连接 ES 客户端 
            RestHighLevelClient esClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http")));
    
            SearchRequest request = new SearchRequest();
            request.indices("user");
            
            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(QueryBuilders.termsQuery("age", "18","20","22"));
            SearchResponse response = esClient.search(request.source(sourceBuilder), RequestOptions.DEFAULT);
            // 查询匹配
            SearchHits hits = response.getHits();
            System.out.println("响应时间:" + response.getTook());
            System.out.println("是否超时:" + response.isTimedOut());
            System.out.println("命中数量:" + hits.getTotalHits());
            System.out.println("MaxScore:" + hits.getMaxScore());
            System.out.println("详细数据:");
            for (SearchHit hit : hits) {
                // 输出每条查询的结果信息
                System.out.println(hit.getSourceAsString());
            }
    
            // 关闭 ES 客户端
            esClient.close();
        }
    } 
    
    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

    返回结果:

    image-20211115225219987

    # 分页查询













     
     
     
     
     
     

















    public class EsPagesQuery {
    
        public static void main(String[] args) throws IOException {
            // 连接 ES 客户端 
            RestHighLevelClient esClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http")));
    
            // 创建搜索请求对象
            SearchRequest request = new SearchRequest();
            request.indices("user");
            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(QueryBuilders.matchAllQuery());
            // 分页查询
            // 当前页其实索引(第一条数据的顺序号),from
            sourceBuilder.from(0);
            // 每页显示多少条 size
            sourceBuilder.size(2);
            SearchResponse response = esClient.search(request.source(sourceBuilder), RequestOptions.DEFAULT);
            // 查询匹配
            SearchHits hits = response.getHits();
            System.out.println("响应时间:" + response.getTook());
            System.out.println("是否超时:" + response.isTimedOut());
            System.out.println("命中数量:" + hits.getTotalHits());
            System.out.println("MaxScore:" + hits.getMaxScore());
            System.out.println("详细数据:");
            for (SearchHit hit : hits) {
                // 输出每条查询的结果信息
                System.out.println(hit.getSourceAsString());
            }
            // 关闭 ES 客户端
            esClient.close();
        }
    }
    
    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

    查询两条数据,从第一条开始

    返回结果:

    image-20211115191132172

    # 排序查询













     

     


















    public class EsSortQuery {
    
        public static void main(String[] args) throws IOException {
            // 连接 ES 客户端 
            RestHighLevelClient esClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http")));
    
            // 创建搜索请求对象
            SearchRequest request = new SearchRequest();
            request.indices("user");
            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(QueryBuilders.matchAllQuery());
            // 排序
            sourceBuilder.sort("age", SortOrder.ASC);
            SearchResponse response = esClient.search(request.source(sourceBuilder), RequestOptions.DEFAULT);
            // 查询匹配
            SearchHits hits = response.getHits();
            System.out.println("响应时间:" + response.getTook());
            System.out.println("是否超时:" + response.isTimedOut());
            System.out.println("命中数量:" + hits.getTotalHits());
            System.out.println("MaxScore:" + hits.getMaxScore());
            System.out.println("详细数据:");
            for (SearchHit hit : hits) {
            // 输出每条查询的结果信息
                System.out.println(hit.getSourceAsString());
            }
    
            // 关闭 ES 客户端
            esClient.close();
        }
    }
    
    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

    # 过滤字段













     
     
     
     
     


















    public class EsFilterQuery {
    
        public static void main(String[] args) throws IOException {
            // 连接 ES 客户端 
            RestHighLevelClient esClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http")));
    
            // 创建搜索请求对象
            SearchRequest request = new SearchRequest();
            request.indices("user");
            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(QueryBuilders.matchAllQuery());
            //查询字段过滤
            String[] excludes = {};
            String[] includes = {"username", "age"};
            sourceBuilder.fetchSource(includes, excludes);
            SearchResponse response = esClient.search(request.source(sourceBuilder), RequestOptions.DEFAULT);
            // 查询匹配
            SearchHits hits = response.getHits();
            System.out.println("响应时间:" + response.getTook());
            System.out.println("是否超时:" + response.isTimedOut());
            System.out.println("命中数量:" + hits.getTotalHits());
            System.out.println("MaxScore:" + hits.getMaxScore());
            System.out.println("详细数据:");
            for (SearchHit hit : hits) {
                // 输出每条查询的结果信息
                System.out.println(hit.getSourceAsString());
            }
    
            // 关闭 ES 客户端
            esClient.close();
        }
    }
    
    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

    返回结果:

    image-20211115194156976

    # Bool查询













     
     
     
     
     
     
     
     

















    public class EsBoolQuery {
    
        public static void main(String[] args) throws IOException {
            // 连接 ES 客户端 
            RestHighLevelClient esClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http")));
    
            // 创建搜索请求对象
            SearchRequest request = new SearchRequest();
            request.indices("user");
            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            // 必须包含
            boolQueryBuilder.must(QueryBuilders.matchQuery("age", "30"));
            // 一定不含
            boolQueryBuilder.mustNot(QueryBuilders.matchQuery("useername", "可乐"));
            // 可能包含
            boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "男"));
            sourceBuilder.query(boolQueryBuilder);
            SearchResponse response = esClient.search(request.source(sourceBuilder), RequestOptions.DEFAULT);
            // 查询匹配
            SearchHits hits = response.getHits();
            System.out.println("响应时间:" + response.getTook());
            System.out.println("是否超时:" + response.isTimedOut());
            System.out.println("命中数量:" + hits.getTotalHits());
            System.out.println("MaxScore:" + hits.getMaxScore());
            System.out.println("详细数据:");
            for (SearchHit hit : hits) {
                // 输出每条查询的结果信息
                System.out.println(hit.getSourceAsString());
            }
            // 关闭 ES 客户端
            esClient.close();
        }
    }
    
    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

    返回结果:

    image-20211115192552793

    # 范围查询













     
     
     
     
     
     














    public class EsRangeQuery {
    
        public static void main(String[] args) throws IOException {
            // 连接 ES 客户端 
            RestHighLevelClient esClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http")));
    
            // 创建搜索请求对象
            SearchRequest request = new SearchRequest();
            request.indices("user");
            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
            // 大于等于
            rangeQuery.gte("18");
            // 小于等于
            rangeQuery.lte("24");
            sourceBuilder.query(rangeQuery);
            request.source(sourceBuilder);
            SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
            // 查询匹配
            SearchHits hits = response.getHits();
            System.out.println("took:" + response.getTook());
            System.out.println("timeout:" + response.isTimedOut());
            System.out.println("total:" + hits.getTotalHits());
            System.out.println("MaxScore:" + hits.getMaxScore());
    
            // 关闭 ES 客户端
            esClient.close();
        }
    }
    
    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

    返回结果:

    image-20211115192720374

    # 模糊查询













     

















    public class EsFuzzyQuery {
    
        public static void main(String[] args) throws IOException {
            // 连接 ES 客户端 
            RestHighLevelClient esClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http")));
    
            // 创建搜索请求对象
            SearchRequest request = new SearchRequest();
            request.indices("user");
            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(QueryBuilders.fuzzyQuery("age",2).fuzziness(Fuzziness.ONE));
            SearchResponse response = esClient.search(request.source(sourceBuilder), RequestOptions.DEFAULT);
            // 查询匹配
            SearchHits hits = response.getHits();
            System.out.println("响应时间:" + response.getTook());
            System.out.println("是否超时:" + response.isTimedOut());
            System.out.println("命中数量:" + hits.getTotalHits());
            System.out.println("MaxScore:" + hits.getMaxScore());
            System.out.println("详细数据:");
            for (SearchHit hit : hits) {
                // 输出每条查询的结果信息
                System.out.println(hit.getSourceAsString());
            }
            // 关闭 ES 客户端
            esClient.close();
        }
    }
    
    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

    返回结果:

    image-20211115193520034

    # 高亮查询













     
     
     
     
     
     
     
     





















    public class EsHeightQuery {
    
        public static void main(String[] args) throws IOException {
            // 连接 ES 客户端 
            RestHighLevelClient esClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http")));
    
            // 高亮查询
            SearchRequest request = new SearchRequest().indices("user");
            // 2.创建查询请求体构建器
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            // 构建查询方式:高亮查询
            sourceBuilder.query(QueryBuilders.termsQuery("age","18","20"));
            // 构建高亮字段
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.preTags("<font color='red'>");// 设置标签前缀
            highlightBuilder.postTags("</font>");// 设置标签后缀
            highlightBuilder.field("age");// 设置高亮字段
            //设置高亮构建对象
            sourceBuilder.highlighter(highlightBuilder);
            // 3.客户端发送请求,获取响应对象
            SearchResponse response = esClient.search(request.source(sourceBuilder), RequestOptions.DEFAULT);
            //4.打印响应结果
            SearchHits hits = response.getHits();
            System.out.println("响应时间:" + response.getTook());
            System.out.println("是否超时:" + response.isTimedOut());
            System.out.println("命中数量:" + hits.getTotalHits());
            System.out.println("MaxScore:" + hits.getMaxScore());
            System.out.println("详细数据:");
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                System.out.println(sourceAsString);
                // 打印高亮结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                System.out.println(highlightFields);
            }
            // 关闭 ES 客户端
            esClient.close();
        }
    }
    
    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

    返回结果:

    image-20211115194508951

    # 聚合查询

    # 最大年龄

    public class EsArrgQuery {
    
        public static void main(String[] args) throws IOException {
            // 连接 ES 客户端 
            RestHighLevelClient esClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http")));
    
            // 高亮查询
            SearchRequest request = new SearchRequest().indices("user");
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));
            // 3.客户端发送请求,获取响应对象
            SearchResponse response = esClient.search(request.source(sourceBuilder), RequestOptions.DEFAULT);
            // 4.打印响应结果
            System.out.println(response);
    
            // 关闭 ES 客户端
            esClient.close();
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20

    # 分组统计

    public class EsArrgQuery {
    
        public static void main(String[] args) throws IOException {
            // 连接 ES 客户端 
            RestHighLevelClient esClient = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost",9200,"http")));
    
            // 高亮查询
            SearchRequest request = new SearchRequest().indices("user");
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.aggregation(AggregationBuilders.terms("ageGroupby").field("age"));
            // 3.客户端发送请求,获取响应对象
            SearchResponse response = esClient.search(request.source(sourceBuilder), RequestOptions.DEFAULT);
            // 4.打印响应结果
            SearchHits hits = response.getHits();
            System.out.println(response);
    
            // 关闭 ES 客户端
            esClient.close();
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21

    # 问题

    Exception in thread "main" ElasticsearchStatusException[Elasticsearch exception [type=search_phase_execution_exception, 
    reason=all shards failed]]; nested: ElasticsearchException[Elasticsearch exception [type=illegal_argument_exception, 
    reason=Text fields are not optimised for operations that require per-document field data like aggregations and sorting, so 
    these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [age] 
    in order to load field data by uninverting the inverted index. Note that this can use significant memory.]]; nested: 
    ElasticsearchException[Elasticsearch exception [type=illegal_argument_exception, reason=Text fields are not optimised for 
    operations that require per-document field data like aggregations and sorting, so these operations are disabled by 
    default. Please use a keyword field instead. Alternatively, set fielddata=true on [age] in order to load field data by 
    uninverting the inverted index. Note that this can use significant memory.]];
    
    1
    2
    3
    4
    5
    6
    7
    8
    9

    说明查询的字段是 text 类型,所以报错,只有 keyword 类型的字符串可以分组聚合查询。

    更新时间: 2024/01/17, 05:48:13
    最近更新
    01
    JVM调优
    12-10
    02
    jenkins
    12-10
    03
    Arthas
    12-10
    更多文章>