前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java elasticsearch-rest-high-level-client 根据歌名搜索,创建索引,根据索引ID搜索

java elasticsearch-rest-high-level-client 根据歌名搜索,创建索引,根据索引ID搜索

作者头像
oktokeep
发布2024-10-09 08:50:31
600
发布2024-10-09 08:50:31
举报
文章被收录于专栏:第三方工具

1.pom 导入jar

代码语言:javascript
复制
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.17.4</version>
</dependency>
代码语言:javascript
复制
ElasticSerarchService.java 根据歌名搜索
代码语言:javascript
复制
package com.redis.demo;


import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class ElasticSerarchService {
    public static void main(String[] args) throws Exception{
        RestHighLevelClient client = getClient();


        //查询
        //默认ID
        GetRequest getRequest = new GetRequest("songs_v2", "_doc", "5EnOMYEBLnSF9_D_wh38");
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        System.out.println("根据ID查询="+getResponse.getSourceAsString());


        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("songs_v2");

        //查询所有记录
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(searchSourceBuilder);
//        System.out.println("searchSourceBuilder="+ JSON.toJSONString(searchSourceBuilder));
        //searchSourceBuilder={"query":{"match_all":{"boost":1.0}}}
        System.out.println("searchSourceBuilder="+ searchSourceBuilder);

        //根据条件查询 歌名
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        sourceBuilder.query(QueryBuilders.termQuery("songName", "tianyi"));
//        sourceBuilder.from(0);
//        sourceBuilder.size(5);
//        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//        searchRequest.source(sourceBuilder);
//
//        //{"from":0,"size":5,"timeout":"60s","query":{"term":{"songName":{"value":"tianyi","boost":1.0}}}}
//        //打印输出,而不是JSON.toJSONString方式来输出
//        System.out.println("sourceBuilder="+ sourceBuilder);


        System.out.println("searchRequest="+ JSON.toJSONString(searchRequest));
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

//        RestStatus status = searchResponse.status();
//        TimeValue took = searchResponse.getTook();
//        Boolean terminatedEarly = searchResponse.isTerminatedEarly();
//        boolean timedOut = searchResponse.isTimedOut();
//
//        int totalShards = searchResponse.getTotalShards();
//        int successfulShards = searchResponse.getSuccessfulShards();
//        int failedShards = searchResponse.getFailedShards();
//        for (ShardSearchFailure failure : searchResponse.getShardFailures()) {
//            // failures should be handled here
//            System.out.println("failures should be handled here");
//        }

        SearchHits hits = searchResponse.getHits();
        for (SearchHit hit : hits) {
            // do something with the SearchHit

            String sourceAsString = hit.getSourceAsString();
//            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
//            String documentTitle = (String) sourceAsMap.get("title");
//            List<Object> users = (List<Object>)) sourceAsMap.get("user");
//            Map<String, Object> innerObject =
//                    (Map<String, Object>) sourceAsMap.get("innerObject");
            System.out.println("查询结果sourceAsString=" + sourceAsString);
        }





        close(client);

    }

    private static void close(RestHighLevelClient client) throws IOException {
        client.close();
    }

    private static RestHighLevelClient getClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")));
        return client;
    }
}

IndexTest.java 创建索引

代码语言:javascript
复制
package com.redis.demo.elasticserach;

import com.redis.demo.ElasticSerarchService;
import org.apache.http.HttpHost;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Cancellable;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentFactory;
import org.elasticsearch.xcontent.XContentType;

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

public class IndexTest {
    private static RestHighLevelClient getClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")));
        return client;
    }

    private static void close(RestHighLevelClient client) throws IOException {
        client.close();
    }

    public static void main(String[] args) throws Exception{
        IndexRequest request = new IndexRequest("posts");
        request.id("1");
        String jsonString = "{" +
                "\"user\":\"kimchy\"," +
                "\"postDate\":\"2013-01-30\"," +
                "\"message\":\"trying out Elasticsearch\"" +
                "}";
        request.source(jsonString, XContentType.JSON);
//        request.routing("routing");
//        request.timeout(TimeValue.timeValueSeconds(1));
//        request.timeout("1s");

        RestHighLevelClient client = getClient();
        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        System.out.println("indexResponse1="+indexResponse.getResult());

        //无法重复创建索引
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("user", "kimchy");
        jsonMap.put("postDate", new Date());
        jsonMap.put("message", "trying out Elasticsearch");
        IndexRequest indexRequest = new IndexRequest("posts")
                .id("2").source(jsonMap);

        indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println("indexResponse2="+indexResponse.getResult());

        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject();
        {
            builder.field("user", "kimchy");
            builder.timeField("postDate", new Date());
            builder.field("message", "trying out Elasticsearch");
        }
        builder.endObject();
        IndexRequest indexRequest3 = new IndexRequest("posts")
                .id("3").source(builder);
        indexResponse = client.index(indexRequest3, RequestOptions.DEFAULT);
        System.out.println("indexResponse3="+indexResponse.getResult());
        /**
         * if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
         *
         * } else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
         *
         * }
         */

        IndexRequest indexRequest4 = new IndexRequest("posts")
                .id("4")
                .source("user", "kimchy",
                        "postDate", new Date(),
                        "message", "trying out Elasticsearch");

        ActionListener listener = new ActionListener<IndexResponse>() {
            @Override
            public void onResponse(IndexResponse indexResponse) {
                System.out.println("异步通知结果result =" + indexResponse.getResult());
                System.out.println("异步通知结果id =" + indexResponse.getId());

            }

            @Override
            public void onFailure(Exception e) {
                System.out.println("异步通知结果异常啦" + e.getMessage());
            }
        };

        //异步方式
        Cancellable cancellable = client.indexAsync(indexRequest4, RequestOptions.DEFAULT, listener);


        //处理异常的情况,id重复 主键冲突
        IndexRequest request5 = new IndexRequest("posts")
                .id("1")
                .source("field", "value")
                .setIfSeqNo(10L)
                .setIfPrimaryTerm(20);
        try {
            IndexResponse response = client.index(request5, RequestOptions.DEFAULT);
        } catch(ElasticsearchException e) {
            if (e.status() == RestStatus.CONFLICT) {
                System.out.println("5主键冲突啦" + e.getMessage());

            }
        }

        IndexRequest request6 = new IndexRequest("posts")
                .id("1")
                .source("field", "value")
                .opType(DocWriteRequest.OpType.CREATE);
        try {
            IndexResponse response = client.index(request6, RequestOptions.DEFAULT);
        } catch(ElasticsearchException e) {
            if (e.status() == RestStatus.CONFLICT) {
                System.out.println("6主键冲突啦" + e.getMessage());
            }
        }

        //关闭
        close(client);

    }
}

GetRequestTest.java  根据ID查询

代码语言:javascript
复制
package com.redis.demo.elasticserach;

import com.redis.demo.ElasticSerarchService;
import org.apache.http.HttpHost;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.rest.RestStatus;

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

public class GetRequestTest {
    private static RestHighLevelClient getClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")));
        return client;
    }

    private static void close(RestHighLevelClient client) throws IOException {
        client.close();
    }

    public static void main(String[] args) throws Exception{
        GetRequest getRequest = new GetRequest(
                "posts",
                "100");

        try {
            RestHighLevelClient client = getClient();
            GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
            String index = getResponse.getIndex();
            String id = getResponse.getId();
            if (getResponse.isExists()) {
                long version = getResponse.getVersion();
                String sourceAsString = getResponse.getSourceAsString();
//                Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
//                byte[] sourceAsBytes = getResponse.getSourceAsBytes();
                System.out.println("sourceAsString=" + sourceAsString);
            } else {
                System.out.println("getResponse不存在");
            }

            //关闭
            close(client);

        } catch (ElasticsearchException e) {
            System.out.println("异常"+e.status());
            if (e.status() == RestStatus.NOT_FOUND) {
                System.out.println("未找到"+e.status());
            }
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-06-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
Elasticsearch Service
腾讯云 Elasticsearch Service(ES)是云端全托管海量数据检索分析服务,拥有高性能自研内核,集成X-Pack。ES 支持通过自治索引、存算分离、集群巡检等特性轻松管理集群,也支持免运维、自动弹性、按需使用的 Serverless 模式。使用 ES 您可以高效构建信息检索、日志分析、运维监控等服务,它独特的向量检索还可助您构建基于语义、图像的AI深度应用。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档