Skip to content

Java客户端

ElasticSearchClient 7.16

添加依赖

xml
<dependency>
    <groupId>co.elastic.clients</groupId>
    <artifactId>elasticsearch-java</artifactId>
    <version>7.16.0</version>
</dependency>

构造ElasticsearchClient

yaml
elastic:
  host: 127.0.0.1
  port: 9200
  username: elastic
  password: 123456
java
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Configuration
public class ElasticConfig {

    @Value("${elastic.host:127.0.0.1}")
    String host;

    @Value("${elastic.port:9200}")
    Integer port;

    @Value("${elastic.username:elastic}")
    String username;

    @Value("${elastic.password:123456}")
    String password;

    @Bean
    public RestClient restClient() {
        RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));

        // 设置账号密码
        // 参考:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/_basic_authentication.html
        if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
            builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
        }

        RestClient restClient = builder.build();
        return restClient;
    }

    @Bean
    public RestClientTransport restClientTransport(RestClient restClient) {
        return new RestClientTransport(restClient, new JacksonJsonpMapper());
    }

    @Bean
    public ElasticsearchClient elasticsearchClient(RestClientTransport transport) {
        return new ElasticsearchClient(transport);
    }

}

查询示例

bash
POST /gupaoedu-wxcp-msg-2024-06-*/_search
{
  "size": 1, 
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "from.keyword": "TongXiaoEr"
          }
        },
        {
          "term": {
            "chatType": "1"
          }
        },
        {
          "term": {
            "msgType": "text"
          }
        },
        {
          "match_phrase": {
            "text.content": "好的"
          }
        }
      ]
    }
  },
  "sort": [
    {
      "msgTime": {
        "order": "desc"
      }
    }
  ]
}
json
{
  "took" : 804,
  "timed_out" : false,
  "_shards" : {
    "total" : 19,
    "successful" : 19,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 83,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [
      {
        "_index" : "gupaoedu-wxcp-msg-2024-06-19",
        "_type" : "_doc",
        "_id" : "1012599982130127612_1718777967324_external",
        "_score" : null,
        "_source" : {
          "cropId" : "wwe2d76b4a3b7df43e",
          "msgType" : "text",
          "msgId" : "1012599982130127612_1718777967324_external",
          "roomId" : "",
          "@timestamp" : "2024-06-19T14:19:23.144+08:00",
          "tolist" : [
            "wmuppIEAAAV9D4H5gODlL1qiV5gZwPTQ"
          ],
          "action" : "send",
          "msgTime" : 1718777963144,
          "from" : "TongXiaoEr",
          "text" : {
            "content" : "好的哦"
          },
          "chatType" : "1"
        },
        "sort" : [
          1718777963144
        ]
      }
    ]
  }
}
java
Query q = Query.of(b -> b.bool(b1 -> b1.must(
                Query.of(b2 -> b2.match(m -> m.field("from.keyword").query(t -> t.stringValue("TongXiaoEr")))),
                Query.of(b2 -> b2.term(t -> t.field("chatType").value(FieldValue.of("1")))),
                Query.of(b2 -> b2.term(t -> t.field("msgType").value(FieldValue.of("text")))),
                Query.of(b2 -> b2.matchPhrase(m -> m.field("text.content").query("好的")))
        )
));

// 构建搜索请求
SearchRequest searchRequest = SearchRequest.of(s -> s
        .index("gupaoedu-wxcp-msg-2024-06-*")
        .size(1)
        .query(q)
        .sort(SortOptions.of(so -> so
                .field(f -> f
                        .field("msgTime")
                        .order(SortOrder.Desc)
                )
        ))
);

SearchResponse<Map> searchResponse = client.search(searchRequest, Map.class);

searchResponse.hits().hits().forEach(hit->{
    System.out.println(hit.source().getClass());
    System.out.println(JsonUtils.toPrettyJson(hit.source()));
});

人生感悟