Elasticsearch Java的API学习-02

JavaAPI-环境准备

新建Maven工程

添加依赖 创建POM文件

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>yooomecloud</artifactId>
        <groupId>com.yooome.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-config-elasticsearch-9200</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <!-- SpringBoot整合Web组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--elasticsearch需要依赖-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.7.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.elasticsearch</groupId>
                    <artifactId>elasticsearch</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.elasticsearch.client</groupId>
                    <artifactId>elasticsearch-rest-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>7.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.7.0</version>
        </dependency>
    </dependencies>
</project>

JavaAPI-索引-创建

java 复制代码
	@GetMapping("/elsa/search/{id}")
    public String GetElasticsearch(@PathVariable("id") Integer id) throws IOException {

        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));
        System.out.println(client);
        // 创建索引 - 请求对象
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("user3");
        // 发送请求,获取响应
        CreateIndexResponse response = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        boolean acknowledged = response.isAcknowledged();
        System.out.println("操作状态:" + acknowledged);
        // 关闭客户端连接
        client.close();

        return "get elastic search dsgs " + "server port " + serverPort + " ack " + id + " acknowledged " + acknowledged;
    }

JavaAPI-索引-查询 & 删除
查询

java 复制代码
 	@GetMapping("elas/search/user")
    public String GetIndexResponse() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));

        GetIndexRequest request = new GetIndexRequest("user");
        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);

        return "aliases: " + response.getAliases() + " mappings: " + response.getMappings() + " settings: " + response.getSettings();
    }

删除

java 复制代码
	@GetMapping("/elas/delete")
    public String DeleteIndexResponse() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        DeleteIndexRequest request = new DeleteIndexRequest("user3");
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);

        return "response: " + response.isAcknowledged();
    }

JavaAPI-文档-新增 & 修改
重构

上下文由于频繁使用以下连接 Elasticsearch 和 关闭它的代码,于是个人对它进行重构。

新增

java 复制代码
	@GetMapping("/elas/create/doc")
    public String CreateElasticsearchIndex() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        IndexRequest request = new IndexRequest();
        request.index("user4").id("1000");
        //创建数据对象
        User user = new User();
        user.setAge(18);
        user.setName("zhangsan");
        user.setSex("男");

        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(user);
        // 添加文档数据,数据格式为 JSON 格式
        request.source(s, XContentType.JSON);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println("_index:" + response.getIndex());
        System.out.println("_id:" + response.getId());
        System.out.println("_result:" + response.getResult());

        return "_index:" + response.getIndex() + "_id:" + response.getId() + "_result:" + response.getResult();
    }

修改

java 复制代码
	@GetMapping("/elas/update/doc")
    public String UpdateElasDoc() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        // 修改文档 - 请求对象
        UpdateRequest request = new UpdateRequest();
        // 修改配置参数
        request.index("user4").id("1000");
        // 设置请求体,对数据修改
        request.doc(XContentType.JSON, "sex", "女");
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);

        return "index " + response.getIndex() + " _id " + response.getId() + " _result " + response.getResult();
    }

JavaAPI-文档-查询 & 删除
查询

java 复制代码
 	@GetMapping("/elas/search/doc")
    public String SearchElasDoc() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        // 创建请求对象
        GetRequest request = new GetRequest();
        // 客户端发送请求,获取响应对象
        request.index("user4").id("1000");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);

        client.close();
        return "_index = " + response.getIndex() + " _type = " + response.getType() + " _id = " + response.getId() + " source = " + response.getSource();
    }

删除

java 复制代码
	@GetMapping("/elas/delete/doc")
    public String DeleteElasDoc() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        // 创建请求对象
        DeleteRequest request = new DeleteRequest();

        // 客户端发送请求,获取响应对象
        request.index("user4").id("1000");
        DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);

        client.close();
        return delete.toString();
    }

JavaAPI-文档-批量新增 & 批量删除
批量新增

java 复制代码
  @GetMapping("/elas/batch/add")
    public String BatchAddElasDoc() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        // 创建添加对象
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest().index("user5").id("1001").source(XContentType.JSON,"name","zhangsan"));
        request.add(new IndexRequest().index("user5").id("1002").source(XContentType.JSON,"name","lisi"));
        request.add(new IndexRequest().index("user5").id("1003").source(XContentType.JSON,"name","wangwu"));
        //客户端发送请求,获取响应对象
        BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
        return "took = " + responses.getTook() +" item = " + responses.getItems();
    }

批量删除

java 复制代码
 	@GetMapping("/elas/batch/delete")
    public String BatchDeleteElasDoc() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        // 创建添加对象
        BulkRequest request = new BulkRequest();
        request.add(new DeleteRequest().index("user5").id("1001"));
        request.add(new DeleteRequest().index("user5").id("1002"));
        request.add(new DeleteRequest().index("user5").id("1003"));
        //客户端发送请求,获取响应对象
        BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
        return "took = " + responses.getTook() +" item = " + responses.getItems();
    }

JavaAPI-文档-高级查询-全量查询

先批量增加数据

java 复制代码
	@GetMapping("/elas/batch/add")
    public String BatchAddElasDoc() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        // 创建添加对象
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest().index("user5").id("1001").source(XContentType.JSON,"name","zhangsan"));
        request.add(new IndexRequest().index("user5").id("1002").source(XContentType.JSON,"name","lisi"));
        request.add(new IndexRequest().index("user5").id("1003").source(XContentType.JSON,"name","wangwu"));
        request.add(new IndexRequest().index("user5").id("1004").source(XContentType.JSON,"name","zhaoliu"));
        request.add(new IndexRequest().index("user5").id("1005").source(XContentType.JSON,"name","hanqi"));
        //客户端发送请求,获取响应对象
        BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
        return "took = " + responses.getTook() +" item = " + responses.getItems();
    }

查询所有索引数据

java 复制代码
@GetMapping("/elas/batch/search/index")
    public String BatchSearchElasIndex() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        // 创建添加对象
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("user5");
        // 构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 查询所有数据
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        request.source(sourceBuilder);
        SearchResponse response = client.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());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }
        System.out.println("<<========");
        return "took = " + response.getTook() + " time out = "+ response.isTimedOut() + " total hits = " + hits.getTotalHits() + " max score = " + hits.getMaxScore();
    }

JavaAPI-文档-高级查询-分页查询 & 条件查询 & 查询排序
条件查询

java 复制代码
@GetMapping("/elas/best/search/index")
    public String BestSearchElasIndex() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("user5");
        // 构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.termQuery("name", "zhangsan"));
        request.source(sourceBuilder);
        SearchResponse response = client.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());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }
        System.out.println("<<========");

        return "took = " + response.getTook() + " time out = "+ response.isTimedOut() + " total hits = " + hits.getTotalHits() + " max score = " + hits.getMaxScore();
    }

分页查询

java 复制代码
@GetMapping("/elas/page/search/index")
    public String PageSearchElasIndex() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("user5");
        // 构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        // 分页查询
        // 当前页其实索引(第一条数据的顺序号), from
        sourceBuilder.from(0);

        // 每页显示多少条 size
        sourceBuilder.size(2);

        request.source(sourceBuilder);
        SearchResponse response = client.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());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }
        System.out.println("<<========");

        return "took = " + response.getTook() + " time out = "+ response.isTimedOut() + " total hits = " + hits.getTotalHits() + " max score = " + hits.getMaxScore();
    }

查询排序

java 复制代码
@GetMapping("/elas/sort/order")
    public String SortOrderElas() throws IOException {
        RestHighLevelClient client = 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);
        request.source(sourceBuilder);
        SearchResponse response = client.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());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }
        System.out.println("<<========");

        return "";
    }

JavaAPI-文档-高级查询-组合查询 & 范围查询
组合查询

java 复制代码
@GetMapping("/elas/match/query")
    public void matchQuery() throws IOException {
        RestHighLevelClient client = 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", "20"));
        // 一定不含
        boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "zhangsan"));
        // 可能包含
        boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "男"));
        sourceBuilder.query(boolQueryBuilder);
        request.source(sourceBuilder);
        SearchResponse response = client.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());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }
        System.out.println("<<========");
    }

范围查询

java 复制代码
@GetMapping("/elas/range/query")
    public void RangeQuery() throws IOException {
        RestHighLevelClient client = 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("30");
        // 小于等于
        rangeQuery.lte("40");
        sourceBuilder.query(rangeQuery);
        request.source(sourceBuilder);
        SearchResponse response = client.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());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }
        System.out.println("<<========");
    }

JavaAPI-文档-高级查询-模糊查询 & 高亮查询
模糊查询

java 复制代码
 @GetMapping("/elas/fuzzy/query")
    public void fuzzyQuery() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("user");
        // 构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.fuzzyQuery("name", "wangw").fuzziness(Fuzziness.ONE));
        request.source(sourceBuilder);
        SearchResponse response = client.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());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }
        System.out.println("<<========");
    }

高亮查询

java 复制代码
@GetMapping("/elas/high/query")
    public void HighLightSearch() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        // 高亮查询
        SearchRequest request = new SearchRequest().indices("user");
        //2.创建查询请求体构建器
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //构建查询方式:高亮查询
        TermsQueryBuilder termsQueryBuilder =
                QueryBuilders.termsQuery("name","lisi");
        //设置查询方式
        sourceBuilder.query(termsQueryBuilder);
        //构建高亮字段
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");//设置标签前缀
        highlightBuilder.postTags("</font>");//设置标签后缀
        highlightBuilder.field("name");//设置高亮字段
        //设置高亮构建对象
        sourceBuilder.highlighter(highlightBuilder);
        //设置请求体
        request.source(sourceBuilder);
        //3.客户端发送请求,获取响应对象
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //4.打印响应结果
        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 : hits) {
            String sourceAsString = hit.getSourceAsString();
            System.out.println(sourceAsString);
            //打印高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            System.out.println(highlightFields);
        }
        System.out.println("<<::::");
    }

JavaAPI-文档-高级查询-最大值查询 & 分组查询
最大值查询

java 复制代码
 @GetMapping("/elas/maxvalue/query")
    public void MaxValueSearch() throws IOException {
        RestHighLevelClient client = 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"));
        //设置请求体
        request.source(sourceBuilder);
        //3.客户端发送请求,获取响应对象
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //4.打印响应结果
        SearchHits hits = response.getHits();
        System.out.println(response);
        for (SearchHit hit : hits) {
            System.out.println(hit);
        }
    }

分组查询

java 复制代码
@GetMapping("/elas/group/query")
    public void GroupSearch() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        // 高亮查询
        SearchRequest request = new SearchRequest().indices("user");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.aggregation(AggregationBuilders.terms("age_groupby").field("age"));
        //设置请求体
        request.source(sourceBuilder);
        //3.客户端发送请求,获取响应对象
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //4.打印响应结果
        SearchHits hits = response.getHits();
        System.out.println(response);
        for (SearchHit hit : hits) {
            System.out.println(hit);
        }
    }
相关推荐
Dola_Pan3 小时前
Linux文件IO(二)-文件操作使用详解
java·linux·服务器
wang_book3 小时前
Gitlab学习(007 gitlab项目操作)
java·运维·git·学习·spring·gitlab
蜗牛^^O^4 小时前
Docker和K8S
java·docker·kubernetes
从心归零4 小时前
sshj使用代理连接服务器
java·服务器·sshj
IT毕设梦工厂5 小时前
计算机毕业设计选题推荐-在线拍卖系统-Java/Python项目实战
java·spring boot·python·django·毕业设计·源码·课程设计
Ylucius6 小时前
动态语言? 静态语言? ------区别何在?java,js,c,c++,python分给是静态or动态语言?
java·c语言·javascript·c++·python·学习
不是笨小孩i6 小时前
Git常用指令
大数据·git·elasticsearch
七夜zippoe6 小时前
分布式系统实战经验
java·分布式
是梦终空6 小时前
JAVA毕业设计176—基于Java+Springboot+vue3的交通旅游订票管理系统(源代码+数据库)
java·spring boot·vue·毕业设计·课程设计·源代码·交通订票
落落落sss6 小时前
sharding-jdbc分库分表
android·java·开发语言·数据库·servlet·oracle