import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.json.JsonData;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
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.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.xml.XmlConfiguration;
import org.apache.logging.log4j.core.Logger;
public class ElasticSearchLogApp {
public static void main(String[] args) {
// 初始化Elasticsearch客户端
final ElasticsearchTransport transport = new RestClientTransport(
new HttpAsyncClientBuilder(),
new HttpHost("localhost", 9200, "http"));
final ElasticsearchClient client = new ElasticsearchClient(transport);
// 创建索引请求
final IndexRequest indexRequest = IndexRequest.of("my-index-001")
.id("my-doc-id")
.document(JsonData.buildObject(builder -> {
builder.put("name", "John Doe");
builder.put("age", 30);
builder.put("gender", "male");
}));
// 发送索引请求
client.index(indexRequest, JsonpMapper.build());
// 创建搜索请求
final SearchRequest searchRequest = SearchRequest.of("my-index-001*")
.query(JsonData.buildObject(builder -> {
builder.put("match_all", JsonData.emptyObject());
}));
// 发送搜索请求并打印结果
final SearchResponse searchResponse = client.search(searchRequest, JsonpMapper.build());
System.out.println(searchResponse.hits());
评论已关闭