Elasticsearch-Java操作篇

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

通常情况下,都是使用编程语言来操作es,本篇带来如何用java操作es。文章来源地址https://www.toymoban.com/news/detail-527490.html

创建maven项目导入依赖

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.17.5</version>
        </dependency>
        <!-- elasticsearch 的客户端 -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.17.5</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>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.80</version>
        </dependency>

准备

POST /student/_doc/1001
{
"name":"zhangsan",
"nickname":"zhangsan",
 "sex":"男",
 "age":30
}
POST /student/_doc/1002
{
"name":"lisi",
"nickname":"lisi",
 "sex":"男",
 "age":20 
  
}
POST /student/_doc/1003
{
"name":"wangwu",
 "nickname":"wangwu",
 "sex":"女",
 "age":40 
  
}
POST /student/_doc/1004
{
"name":"zhangsan1",
"nickname":"zhangsan1",
 "sex":"女",
 "age":50 
  
}
POST /student/_doc/1005
{
"name":"zhangsan2",
"nickname":"zhangsan2",
 "sex":"女",
 "age":30 
}
public class User {
    private String name;
    private Integer age;
    private String sex;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public User(String name, Integer age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public User() {
    }
}

连接操作

  @Before
    public void init() {
        client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("q1", 9200, "http"),
                new HttpHost("q1", 9200, "http"),
                new HttpHost("q1", 9200, "http")));
    }

    @After
    public void close() throws IOException {
        client.close();
    }

索引操作

创建索引

@Test
    public void createIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("user");
        //在这里可以对索引创建时候进行一些细化设置,例如下行设置索引分片为5
        //request.settings(Settings.builder().put("number_of_shards", "5").build());
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println("操作状态:" + response.isAcknowledged());
    }

查询索引

   @Test
    public void searchIndex() throws IOException {
        //* 查看所有,也可以指定具体索引名称
        GetIndexRequest request = new GetIndexRequest("*");
        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
        //下面的key都代表索引
        System.out.println("aliases:" + response.getAliases());
        System.out.println("mappings:" + response.getMappings());
        System.out.println("settings:" + response.getSettings());
    }

删除索引

    @Test
    public void deleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("user");
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println("操作结果 : " + response.isAcknowledged());
    }

文档操作

创建文档

   @Test
    public void createDocument() throws IOException {
        //重复新增相当于修改
        IndexRequest request = new IndexRequest();
        //如果id不指定就是用默认随机字符串
        request.index("user").id("1");
        User user = new User("法外狂徒张三", 35, "男");
        //这里将user写成json字符串进行导入,任何转json包都可以使用
        request.source(JSONObject.toJSONString(user), 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());
    }

批量创建文档

  @Test
    public void batchCreateDocuments() throws IOException {
        //批量新增,但是可以重复新增,相当于修改
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "zhangsan"));
        request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "name", "lisi"));
        request.add(new IndexRequest().index("user").id("1006").source(XContentType.JSON, "name", "wangwu"));
        BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
        System.out.println("took:" + responses.getTook());
        BulkItemResponse[] items = responses.getItems();
        for (BulkItemResponse item : items) {
            System.out.println("items:" + item.getResponse());
        }
    }

更新文档

@Test
    public void updateDocument() throws IOException {
        UpdateRequest request = new UpdateRequest();
        request.index("user").id("gXjB94EBIFfPOUf19kof");
        //后面跟key,value 按照顺序
        request.doc(XContentType.JSON, "sex", "男", "age", 14);
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println("_index:" + response.getIndex());
        System.out.println("_id:" + response.getId());
        System.out.println("_result:" + response.getResult());
    }

查询文档

    @Test
    public void searchDocument() throws IOException {
        //查询单条文档
        GetRequest request = new GetRequest().index("user").id("gXjB94EBIFfPOUf19kof");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        System.out.println("_index:" + response.getIndex());
        System.out.println("_type:" + response.getType());
        System.out.println("_id:" + response.getId());
        System.out.println("source:" + response.getSourceAsString());
    }

删除文档

@Test
    public void deleteDocument() throws IOException {
        DeleteRequest request = new DeleteRequest().index("user").id("1");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
    }

批量删除文档

 @Test
    public void batchDeleteDocuments() throws IOException {
        BulkRequest request = new BulkRequest();
        request.add(new DeleteRequest().index("user").id("1001"));
        request.add(new DeleteRequest().index("user").id("1002"));
        request.add(new DeleteRequest().index("user").id("1003"));
        BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
        System.out.println("took:" + responses.getTook());
        System.out.println("items:" + responses.getItems());
    }

查询操作

查询所有索引数据

@Test
    public void searchAllIndexes() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("fluid,earthquake_basic_info");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        //7版本默认只查询10000条,设置true查询所有,否则 hits.getTotalHits() 只有10000
        sourceBuilder.trackTotalHits(true);
        //默认十条
        sourceBuilder.size(20);
        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("<<========");
    }

查询关键字

@Test
    public void termQuery() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("student");
        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("<<========");
    }

分页查询

 @Test
    public void limitQuery() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("student");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        sourceBuilder.from(0);
        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("<<========");
    }

排序

 @Test
    public void sortQuery() throws IOException {
        SearchRequest request = new SearchRequest();
        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("<<========");
    }

过滤

@Test
    public void filterAttributes() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("student");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        String[] excludes = {}; //不想要的字段
        String[] includes = {"name", "age"}; //想要的字段
        sourceBuilder.fetchSource(includes, excludes);
        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("<<========");
    }

bool查询

@Test
    public void boolQuery() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("student");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //必须包含
        boolQueryBuilder.must(QueryBuilders.matchQuery("age", "30"));
        //一定不含
        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("<<========");
    }

范围查询

@Test
    public void scopeQuery() throws IOException {

        SearchRequest request = new SearchRequest();
        request.indices("student");
        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("<<========");
    }

模糊查询

@Test
    public void fuzzQuery() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("student");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.fuzzyQuery("name", "zhangsan").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("<<========");
    }

高亮查询

@Test
    public void highLightQuery() throws IOException {
        SearchRequest request = new SearchRequest().indices("student");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name", "zhangsan");
        sourceBuilder.query(termsQueryBuilder);
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");//设置标签前缀
        highlightBuilder.postTags("</font>");//设置标签后缀
        highlightBuilder.field("name");//设置高亮字段
        sourceBuilder.highlighter(highlightBuilder);
        request.source(sourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println("took::" + response.getTook());
        System.out.println("time_out::" + response.isTimedOut());
        System.out.println("total::" + hits.getTotalHits());
        System.out.println("max_score::" + hits.getMaxScore());
        System.out.println("hits::::>>");
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            System.out.println(sourceAsString);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            System.out.println(highlightFields);
        }
        System.out.println("<<::::");
    }

聚合查询

@Test
    public void maxAge() throws IOException {
        SearchRequest request = new SearchRequest().indices("student");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));
        request.source(sourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(response);
    }

分组查询

@Test
    public void Group() throws IOException {
        SearchRequest request = new SearchRequest().indices("student");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.aggregation(AggregationBuilders.terms("age_groupby").field("age"));
        request.source(sourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(response);
    }

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

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

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

相关文章

  • java操作ElasticSearch之批量操作

    出现: 版本冲突、文档类型不对、JAR包与使用的API不一致或其他问题。都可参考以下连接。 ElasticSearch超级实用API描述 以上代码需要变动一下,将一些参数替换掉。

    2024年02月16日
    浏览(45)
  • 【ElasticSearch】ElasticSearch Java API的使用——常用索引、文档、查询操作(二)

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

    2024年01月16日
    浏览(82)
  • Java 操作ElasticSearch

            Java REST提供了两种风格的客户端连接工具,Java High Level REST Client、Java Low Level REST Client,这里我就不去细说Java Low Level REST Client了,因为这我确实没用到过,也不是很了解,我说一下Java High Level REST Client。         首先如果你喜欢看官方文档的话,我把地址粘贴

    2024年02月06日
    浏览(36)
  • Java操作Elasticsearch(新增数据)

    天行健,君子以自强不息;地势坤,君子以厚德载物。 每个人都有惰性,但不断学习是好好生活的根本,共勉! 文章均为学习整理笔记,分享记录为主,如有错误请指正,共同学习进步。 首先需要准备好elasticsearch和kibana elasticsearch的下载、安装、使用可参考:Elasticsearch安装

    2024年02月03日
    浏览(38)
  • java Api操作Elasticsearch

    本次使用 elasticsearch 版本为7.17.0, 建议使用 7.X 版本 ,8.1.2版本会遇到一些 Springboot(本人使用版本2.6.6) 版本不兼容的问题。此文章会列举一个例子。 我们在测试类中先创建一个客户端,用来向 ES 发送请求 测试代码如下: 控制台输出信息如下: 此处会遇到坑: 运行之后

    2023年04月09日
    浏览(37)
  • Java API批量操作Elasticsearch

    @Test public void batchAddIndex() throws IOException { BulkRequestBuilder bulkRequest = client .prepareBulk(); bulkRequest.add( client .prepareIndex( “batch_test1” , “batch” , “1” ) .setSource( jsonBuilder () .startObject() .field( “user” , “lzq” ) .field( “postDate” , new Date()) .field( “message” , “trying out Elasticsearch”

    2024年04月09日
    浏览(43)
  • Java操作Elasticsearch进行数据检索

    1.安装依赖 (注意版本要和自己安装的es版本对应)          打开发现部分依赖和我们es版本不一致,是因为springboot指定了版本,我们需要更换为自己对应版本。 1.1、改为自己es对应版本  2.编写配置类 3.配置类添加请求选项 4、测试 4.1、存储数据到es  4.2、检索数据  

    2024年02月16日
    浏览(42)
  • ElasticSearch Java API 基本操作

    ElasticSearch Java API是ES官方在8.x版本推出的新java api,也可以适用于7.17.x版本的es。 本文主要参考了相关博文,自己手动编写了下相关操作代码,包括更新mappings等操作的java代码。 代码示例已上传github。 elasticsearch 版本: 7.17.9 ,修改 /elasticsearch-7.17.9/config/elasticsearch.yml ,新增

    2024年02月08日
    浏览(44)
  • ElasticSearch基础篇-Java API操作

    演示代码 创建连接 POM依赖 建立连接 索引操作 创建索引 删除索引 查询索引 文档操作 创建文档 删除文档 更新文档 查询文档 批量操作 批量新增 批量删除 高级操作 聚合查询 组合查询 条件查询 过滤查询 模糊查询 高亮查询 全量查询 结果排序 分页查询 范围查询

    2024年02月10日
    浏览(35)
  • Java根据id对elasticsearch查询操作

    一、根据一个id查询 二、根据多个ids查询

    2024年02月12日
    浏览(51)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包