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

2022/6/12 1:20:22

本文主要是介绍java elasticsearch-rest-high-level-client 根据歌名搜索,创建索引,根据索引ID搜索,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.pom 导入jar

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.17.4</version>
</dependency>

ElasticSerarchService.java 根据歌名搜索
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 创建索引

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查询

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());
            }
        }
    }
}

 



这篇关于java elasticsearch-rest-high-level-client 根据歌名搜索,创建索引,根据索引ID搜索的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程