以下备忘 Spring Boot 项目使用 transport client 连接 Elasticsearch 的方式。
添加如下依赖:
<dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>5.4.1</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>5.4.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.11.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.11.1</version> </dependency>
注意,这里对 log4j
的依赖引用,是为了解决以下报错:
NoClassDefFoundError: org/apache/logging/log4j/Logger
@Slf4j @Configuration public class ESClientConfiguration { @Bean public Client client() { TransportClient client = null; try { Settings settings = Settings.builder() .put("client.transport.sniff", true) .put("cluster.name", "xxxx") .put("client.transport.ping_timeout", "3s") .build(); client = new PreBuiltTransportClient(settings) .addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("xxx.xxx.xxx.xxx", 9300))) .addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("xxx.xxx.xxx.xxx", 9300))) .addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("xxx.xxx.xxx.xxx", 9300))); return client; } catch (Throwable e) { log.error("@@@@", e); } return client; } }
@Autowired private Client client; SearchResponse searchResponse = client.prepareSearch("index").setQuery( QueryBuilders.boolQuery().should(xxx).should(xxx) ).get(); SearchHit[] hits = searchResponse.getHits().getHits();