ElasticsearchClient示例

package com.example.whybackend;

public class Question {

    public Integer Id;

    public String Title;

    public String Answer;
}
package com.example.whybackend.elasticsearchclient;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;

public class ElasticSearchConfig {

    public ElasticsearchClient getClient(){
        // 创建低级客户端
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200)).build();

        // 使用Jackson映射器创建传输层
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());

        // 创建API客户端
        ElasticsearchClient client = new ElasticsearchClient(transport);
        return client;
    }

}

 

@Test
    void esCreateDoc() throws IOException{
        ElasticSearchConfig cfg = new ElasticSearchConfig();
        ElasticsearchClient client = cfg.getClient();

        Question q = new Question();
        q.Id = 3;
        q.Answer = "23333";
        q.Title = "佩罗西";

// 构建一个创建Doc的请求
        CreateResponse createResponse = client.create(e->e.index("question").id("3").document(q));
// 打印请求结果
        System.out.println(createResponse.result());
// 打印结果
    }
@Test
    void esSearchDoc() throws IOException{
        ElasticSearchConfig cfg = new ElasticSearchConfig();
        ElasticsearchClient client = cfg.getClient();

        SearchResponse search = client.search(s -> s
                        .index("question")
                        .query(q -> q
                                .match(t -> t
                                        .field("Title")
                                        .query("佩罗西")
                                )
                        ),
                Question.class);
        System.out.println("0");
    }

你可能感兴趣的:(java,jvm,elasticsearch)