ElasticSearch基础篇-Java API操作

这篇具有很好参考价值的文章主要介绍了ElasticSearch基础篇-Java API操作。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

ElasticSearch基础-Java API操作

ElasticSearch基础篇-Java API操作,ElasticSearch,elasticsearch,java

演示代码文章来源地址https://www.toymoban.com/news/detail-695863.html

创建连接
POM依赖
<?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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.vmware</groupId>
    <artifactId>spring-custom</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.8.0</version>
        </dependency>
        <!-- elasticsearch 的客户端 -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.8.0</version>
        </dependency>
        <!-- elasticsearch 依赖 2.x 的 log4j -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.9</version>
        </dependency>
        <!-- junit 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.9</version>
        </dependency>
    </dependencies>
</project>
建立连接
package com.vmware.elastic;

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

import java.io.IOException;

/**
 * @apiNote 演示创建elastic客户端,与关闭连接
 */

public class HelloElasticSearch {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );

        client.close();
    }
}
索引操作
创建索引
package com.vmware.elastic.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;

/**
 * @apiNote 演示创建索引
 */
public class IndexCreate {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        CreateIndexRequest request = new CreateIndexRequest("vmware");
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println("索引操作:" + response.isAcknowledged());
        client.close();
    }
}
删除索引
package com.vmware.elastic.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;

/**
 * @apiNote 演示删除索引
 */
public class IndexDelete {
    public static void main(String[] args) throws Exception {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        DeleteIndexRequest request = new DeleteIndexRequest("vmware");
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());//acknowledged表示操作是否成功
        client.close();
    }
}
查询索引
package com.vmware.elastic.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.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;

/**
 * @apiNote 演示查询索引
 */
public class IndexQuery {
    public static void main(String[] args) throws Exception {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        GetIndexRequest request = new GetIndexRequest("vmware");
        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
        System.out.println(response.getAliases());//获取别名
        //{vmware=[]}
        System.out.println(response.getMappings());//获取索引映射
        //{vmware=org.elasticsearch.cluster.metadata.MappingMetadata@9b2cfd3c}
        System.out.println(response.getSettings());//获取索引设置
        //{vmware={"index.creation_date":"1690635515922","index.number_of_replicas":"1","index.number_of_shards":"1","index.provided_name":"vmware","index.uuid":"HtIuUNNnTTyz9CT2oz0Lww","index.version.created":"7060299"}}
        client.close();
    }
}
文档操作
创建文档
package com.vmware.elastic.document;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.vmware.elastic.entity.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteResponse;
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.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;

/**
 * @apiNote 演示创建文档
 */
public class DocumentCreate {
    private static Gson gson = new Gson();

    public static void main(String[] args) throws Exception {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        IndexRequest request = new IndexRequest();
        request.index("vmware");
        request.id("1001");
        User user = new User();
        user.setName("张三");
        user.setAge(18);
        user.setSex("男");
        //es client操作索引需要将java对象转为json格式
        String json = gson.toJson(user);
        request.source(json, XContentType.JSON);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        DocWriteResponse.Result result = response.getResult();
        System.out.println(result);//CREATED
        client.close();
    }
}
删除文档
package com.vmware.elastic.document;

import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
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;

/**
 * @apiNote 演示删除文档
 */
public class DocumentDelete {
    public static void main(String[] args) throws Exception{
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        DeleteRequest request=new DeleteRequest("vmware","1001");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.getResult());//DELETED
        client.close();
    }
}
更新文档
package com.vmware.elastic.document;

import com.google.gson.Gson;
import com.vmware.elastic.entity.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
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;

/**
 * @apiNote 演示更新文档
 */
public class DocumentUpdate {

    public static void main(String[] args) throws Exception {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        UpdateRequest request = new UpdateRequest();
        request.index("vmware");
        request.id("1001");
        request.doc(XContentType.JSON,"name","李四");
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        DocWriteResponse.Result result = response.getResult();
        System.out.println(result);//UPDATED
        client.close();
    }
}
查询文档
package com.vmware.elastic.document;

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;

/**
 * @apiNote 演示查询文档
 */
public class DocumentQuery {
    public static void main(String[] args) throws Exception {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        GetRequest request = new GetRequest("vmware", "1001");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());//{"name":"李四","age":18,"sex":"男"}
        client.close();
    }
}
批量操作
批量新增
package com.vmware.elastic.batch;

import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
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;

/**
 * @apiNote 批量创建文档
 */
public class DocumentBatchCreate {
    public static void main(String[] args) throws Exception {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        BulkRequest request = new BulkRequest("vmware");//bulk:大批的
        request.add(new IndexRequest().id("1005").source(XContentType.JSON,"name","wangwu","age",30));
        request.add(new IndexRequest().id("1006").source(XContentType.JSON,"name","wangwu2","age",40));
        request.add(new IndexRequest().id("1007").source(XContentType.JSON,"name","wangwu33","age",50));
        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.getTook());//6ms
        System.out.println(response.getItems());//[Lorg.elasticsearch.action.bulk.BulkItemResponse;@6bb4dd34
        client.close();
    }
}
批量删除
package com.vmware.elastic.batch;

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.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

/**
 * @apiNote 批量删除
 */
public class DocumentBatchDelete {
    public static void main(String[] args) throws Exception{
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        BulkRequest request = new BulkRequest("vmware");//bulk:大批的
        request.add(new DeleteRequest().id("1005"));
        request.add(new DeleteRequest().id("1006"));
        request.add(new DeleteRequest().id("1007"));
        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.getTook());//8ms
        System.out.println(response.getItems());//[Lorg.elasticsearch.action.bulk.BulkItemResponse;@624ea235
        client.close();
    }
}
高级操作
聚合查询
package com.vmware.elastic.high;

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.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.MaxAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.util.List;

/**
 * @apiNote 聚合查询
 */
public class DocumentAggregateQuery {
    public static void main(String[] args) throws Exception {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        SearchRequest request = new SearchRequest("vmware");
        //最大值查询
//        MaxAggregationBuilder maxAggregationBuilder = AggregationBuilders.max("maxAge").field("age");

        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");//分组查询

        request.source(new SearchSourceBuilder().aggregation(termsAggregationBuilder));//构建查询,设置为全量查询
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        for (Aggregation aggregation : response.getAggregations()) {
            ParsedLongTerms terms = (ParsedLongTerms) aggregation;
            List<? extends Terms.Bucket> buckets = terms.getBuckets();
            for (Terms.Bucket bucket : buckets) {
                System.out.println(bucket.getKeyAsString() + ":" + bucket.getDocCount());
            }
        }

        client.close();
    }
}
组合查询
package com.vmware.elastic.high;

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.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

/**
 * @apiNote 组合查询
 */
public class DocumentCombinationQuery {
    public static void main(String[] args) throws Exception{
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        SearchRequest request = new SearchRequest("vmware");
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //构建组合查询条件 must:全部满足
//        boolQuery.must(QueryBuilders.matchQuery("name","王五"));
//        boolQuery.must(QueryBuilders.matchQuery("age",30));
        //构建组合条件 should:满足任意一个条件即可
//        boolQuery.should(QueryBuilders.matchQuery("age",30));
//        boolQuery.should(QueryBuilders.matchQuery("age",50));
        //构建组合查询条件 mushNot:不满足条件
        boolQuery.mustNot(QueryBuilders.matchQuery("age",30));

        request.source(new SearchSourceBuilder().query(boolQuery));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();//获取查询结果
        TimeValue took = response.getTook(); //获取响应时间
        System.out.println("响应时间:" + took);
        for (SearchHit hit : hits) {
            System.out.println(hit);
        }
        client.close();
    }
}
条件查询
package com.vmware.elastic.high;

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.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

/**
 * @apiNote 条件查询
 *
 * 响应时间:0s
 * {
 *   "_index" : "vmware",
 *   "_type" : "_doc",
 *   "_id" : "1005",
 *   "_score" : 1.0,
 *   "_source" : {
 *     "name" : "王五",
 *     "age" : 30
 *   }
 * }
 */
public class DocumentConditionalQuery {
    public static void main(String[] args) throws Exception{
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        SearchRequest request = new SearchRequest("vmware");
        request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age","30")));//设置查询条件为name=王五
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();//获取查询结果
        TimeValue took = response.getTook(); //获取响应时间
        System.out.println("响应时间:" + took);
        for (SearchHit hit : hits) {
            System.out.println(hit);//
        }
        client.close();
    }
}
过滤查询
package com.vmware.elastic.high;

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.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

/**
 * @apiNote 过滤查询
 */
public class DocumentFilterQuery {
    public static void main(String[] args) throws Exception {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        SearchRequest request = new SearchRequest("vmware");
        String[] includes = {"name","age"};//需要包含的字段
        String[] excludes = {};            //需要排除的字段
        request.source(
                new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).fetchSource(includes, excludes)//添加过滤条件
        );
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();//获取查询结果
        TimeValue took = response.getTook(); //获取响应时间
        System.out.println("响应时间:" + took);
        for (SearchHit hit : hits) {
            System.out.println(hit);
        }
        client.close();
    }
}
模糊查询
package com.vmware.elastic.high;

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.common.unit.Fuzziness;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

/**
 * @apiNote 模糊查询
 */
public class DocumentFuzzyQuery {
    public static void main(String[] args) throws Exception{
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        SearchRequest request = new SearchRequest("vmware");
        //设置模糊查询 Fuzziness.ONE:差一个字也可以查询出来  注意:需要字段设置为keyword类型,否则es会对查询条件进行分词导致模糊查询失效
        FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("name", "王五").fuzziness(Fuzziness.ONE);

        request.source(new SearchSourceBuilder().query(fuzzyQueryBuilder));//构建查询,设置为全量查询
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();//获取查询结果
        TimeValue took = response.getTook(); //获取响应时间
        System.out.println("响应时间:" + took);
        for (SearchHit hit : hits) {
            System.out.println(hit);
        }
        client.close();
    }
}
高亮查询
package com.vmware.elastic.high;

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.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;

/**
 * @apiNote 高亮查询
 */
public class DocumentHighLightQuery {
    public static void main(String[] args) throws Exception{
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        SearchRequest request = new SearchRequest("vmware");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "wangwu");//注意:高亮不支持中文
        searchSourceBuilder.query(termQueryBuilder);
        //构建高亮查询
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<fort style='color:red'>");//设置前缀标签
        highlightBuilder.postTags("</fort>");//设置后缀标签
        highlightBuilder.field("name");//设置高亮字段
        searchSourceBuilder.highlighter(highlightBuilder);

        request.source(searchSourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();//获取查询结果
        TimeValue took = response.getTook(); //获取响应时间
        System.out.println("响应时间:" + took);
        for (SearchHit hit : hits) {
            System.out.println(hit);//<fort style='color:red'>wangwu</fort>
        }
        client.close();
    }
}
全量查询
package com.vmware.elastic.high;

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.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

/**
 * @apiNote 全量查询
 *
 * 响应时间:0s
 * {
 *   "_index" : "vmware",
 *   "_type" : "_doc",
 *   "_id" : "1005",
 *   "_score" : 1.0,
 *   "_source" : {
 *     "name" : "王五",
 *     "age" : 30
 *   }
 * }
 * {
 *   "_index" : "vmware",
 *   "_type" : "_doc",
 *   "_id" : "1006",
 *   "_score" : 1.0,
 *   "_source" : {
 *     "name" : "赵六",
 *     "age" : 40
 *   }
 * }
 * {
 *   "_index" : "vmware",
 *   "_type" : "_doc",
 *   "_id" : "1007",
 *   "_score" : 1.0,
 *   "_source" : {
 *     "name" : "陈⑦",
 *     "age" : 50
 *   }
 * }
 */
public class DocumentMatchAllQuery {
    public static void main(String[] args) throws Exception {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        SearchRequest request = new SearchRequest("vmware");
        request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));//构建查询,设置为全量查询
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();//获取查询结果
        TimeValue took = response.getTook(); //获取响应时间
        System.out.println("响应时间:" + took);
        for (SearchHit hit : hits) {
            System.out.println(hit);
        }
        client.close();
    }
}
结果排序
package com.vmware.elastic.high;

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.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;

/**
 * @apiNote 对返回结果排序
 */
public class DocumentOrderQuery {
    public static void main(String[] args) throws Exception{
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        SearchRequest request = new SearchRequest("vmware");
        request.source(
                new SearchSourceBuilder().query(QueryBuilders.matchAllQuery())
                        .sort("age", SortOrder.ASC)//设置排序规则
        );
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();//获取查询结果
        TimeValue took = response.getTook(); //获取响应时间
        System.out.println("响应时间:" + took);
        for (SearchHit hit : hits) {
            System.out.println(hit);
        }
        client.close();
    }
}
分页查询
package com.vmware.elastic.high;

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.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

/**
 * @apiNote 分页查询
 */
public class DocumentPagingQuery {
    public static void main(String[] args) throws Exception{
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        SearchRequest request = new SearchRequest("vmware");
        request.source(
                new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).from(0).size(2) //设置分页
        );
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();//获取查询结果
        TimeValue took = response.getTook(); //获取响应时间
        System.out.println("响应时间:" + took);
        for (SearchHit hit : hits) {
            System.out.println(hit);
        }
        client.close();
    }
}
范围查询
package com.vmware.elastic.high;

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.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

/**
 * @apiNote 范围查询
 */
public class DocumentRangeQuery {
    public static void main(String[] args) throws Exception{
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        SearchRequest request = new SearchRequest("vmware");
        RangeQueryBuilder queryBuilder = QueryBuilders.rangeQuery("age").gte(40).lt(50);//构建范围查询 大于等于40小于50
        request.source(new SearchSourceBuilder().query(queryBuilder));

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();//获取查询结果
        TimeValue took = response.getTook(); //获取响应时间
        System.out.println("响应时间:" + took);
        for (SearchHit hit : hits) {
            System.out.println(hit);
        }
        client.close();
    }
}

到了这里,关于ElasticSearch基础篇-Java API操作的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【ElasticSearch】ElasticSearch Java API的使用——常用索引、文档、查询操作(二)

    Elaticsearch ,简称为es,es是一个开源的 高扩展 的 分布式全文检索引擎 ,它可以近乎 实时的存储 、 检索数据; 本身扩展性很好,可以扩展到上百台服务器,处理PB级别(大数据时代)的数据。es也使用java开发并使用Lucene作为其核心来实现所有索引和搜索的功能,但是它的 目的

    2024年01月16日
    浏览(91)
  • Elasticsearch Java REST Client 批量操作(Bulk API)

    上一篇:Elasticsearch Java REST Client Term Vectors API 下一篇:Elasticsearch Java REST Client Search APIs 查询 BulkRequest可用于使用单个请求执行多个索引、更新和/或删除操作。 它需要至少一个操作添加到 Bulk 请求中: multiGetAPI 在单个 http 请求中并行执行多个请求get 。 MultiGetRequest,添加 `M

    2024年02月11日
    浏览(51)
  • Elasticsearch基础学习(Java API 实现增删查改)

    ElasticSearch,简称为ES, ES是一个开源的高扩展的分布式全文搜索引擎。它可以近乎实时的存储、检索数据;本身扩展性很好,可以扩展到上百台服务器,处理PB级别的数据。 物理设计: ElasticSearch 在后台把每个索引划分成多个分片,每份分片可以在集群中的不同服务器间迁移

    2024年02月01日
    浏览(81)
  • 最新版ES8的client API操作 Elasticsearch Java API client 8.0

    作者:ChenZhen 本人不常看网站消息,有问题通过下面的方式联系: 邮箱:1583296383@qq.com vx: ChenZhen_7 我的个人博客地址:https://www.chenzhen.space/🌐 版权:本文为博主的原创文章,本文版权归作者所有,转载请附上原文出处链接及本声明。📝 如果对你有帮助,请给一个小小的s

    2024年02月04日
    浏览(41)
  • 4、Elasticsearch7.6.1 Java api操作ES(CRUD、两种分页方式、高亮显示)和Elasticsearch SQL详细示例

    1、介绍lucene的功能以及建立索引、搜索单词、搜索词语和搜索句子四个示例实现 2、Elasticsearch7.6.1基本介绍、2种部署方式及验证、head插件安装、分词器安装及验证 3、Elasticsearch7.6.1信息搜索示例(索引操作、数据操作-添加、删除、导入等、数据搜索及分页) 4、Elasticsearch7

    2024年02月16日
    浏览(79)
  • Elasticsearch RestHighLevelClient 已标记为被弃用 它的替代方案 Elasticsearch Java API Client 的基础教程及迁移方案

    在Elasticsearch7.15版本之后,Elasticsearch官方将它的高级客户端 RestHighLevelClient 标记为弃用状态。同时推出了全新的Java API客户端 Elasticsearch Java API Client ,该客户端也将在Elasticsearch8.0及以后版本中成为官方推荐使用的客户端。 Elasticsearch Java API Client 支持除 Vector tile search API 和

    2024年01月16日
    浏览(41)
  • Java SpringBoot API 实现ES(Elasticsearch)搜索引擎的一系列操作(超详细)(模拟数据库操作)

    小编使用的是elasticsearch-7.3.2 基础说明: 启动:进入elasticsearch-7.3.2/bin目录,双击elasticsearch.bat进行启动,当出现一下界面说明,启动成功。也可以访问http://localhost:9200/ 启动ES管理:进入elasticsearch-head-master文件夹,然后进入cmd命令界面,输入npm run start 即可启动。访问http

    2024年02月04日
    浏览(57)
  • 【Elasticsearch学习笔记五】es常用的JAVA API、es整合SpringBoot项目中使用、利用JAVA代码操作es、RestHighLevelClient客户端对象

    目录 一、Maven项目集成Easticsearch 1)客户端对象 2)索引操作 3)文档操作 4)高级查询 二、springboot项目集成Spring Data操作Elasticsearch 1)pom文件 2)yaml 3)数据实体类 4)配置类 5)Dao数据访问对象 6)索引操作 7)文档操作 8)文档搜索 三、springboot项目集成bboss操作elasticsearch

    2023年04月09日
    浏览(51)
  • ElasticSearch系列——Elasticsearch Java API Client

    这是用于Elasticsearch的官方Java API客户端的文档。客户端为所有Elasticsearch API提供强类型请求和响应。我们要注意原来的HighRestAPIClient以及停用了,这是趋势,包括SpringData-ElasticSearch4.4.5之后配合ES8的推出也会更换 https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/7.17/indexing.html

    2024年02月01日
    浏览(44)
  • Elasticsearch-06-Elasticsearch Java API Client-Elasticsearch 8.0 的api

    在 Elasticsearch7.15版本之后,Elasticsearch官方将它的 高级客户端 RestHighLevelClient 标记为弃用状态。同时推出了全新的 Java API客户端 Elasticsearch Java API Client ,该客户端也将在 Elasticsearch8.0及以后版本中成为官方推荐使用的客户端。 Elasticsearch Java API Client 支持除 Vector tile search API 和

    2024年04月11日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包