以下备忘 Spring Boot 项目连接 Elasticsearch 的方式。

1. Transport Client 方式

1.1 Pom.xml

添加如下依赖:

<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

1.2 添加 Client Bean

@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;
    }
}

注:【 Transport Client 使用 TCP 端口 】Elasticsearch Http 端口和 TCP 端口不同,切勿写错。

1.3 使用

@Autowired
private Client client;

SearchResponse searchResponse = client.prepareSearch("index").setQuery(
   QueryBuilders.boolQuery().should(xxx).should(xxx)
).get();
SearchHit[] hits = searchResponse.getHits().getHits();

2. Jest 方式

2.1 Pom.xml

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>5.4.1</version>
</dependency>
<dependency>
    <groupId>io.searchbox</groupId>
    <artifactId>jest</artifactId>
    <version>5.3.3</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>

2.2 添加 Client Bean

@Configuration
public class ESJestClientConfiguration {

    @Bean("JestClient")
    public JestClient client() {
        Set<String> hosts = new HashSet<>(Arrays.asList("host1:port1", "host2:port2"));
        JestClientFactory factory = new JestClientFactory();
        Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
        factory.setHttpClientConfig(
                new HttpClientConfig.Builder(hosts)
                        .gson(gson)
                        .multiThreaded(true)
                        .defaultMaxTotalConnectionPerRoute(2)
                        .maxTotalConnection(10)
                        .build()
        );
        return factory.getObject();
    }
}

注:【 Jest 使用 HTTP 端口 】Elasticsearch Http 端口和 TCP 端口不同,切勿写错。

2.3 使用

@Autowired
private JestClient jestClient;

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(
    QueryBuilders.boolQuery().should(xxx).should(xxx)
);
Search search = new Search.Builder(searchSourceBuilder.toString())
        .addIndex("index")
        .build();
JestResult result = jestClient.execute(search);
List<Model> models = result.getSourceAsObjectList(Model.class);

参考连接

  1. elasticsearch bool query combine must with OR - Stack Overflow
  2. How to query for null values? - Elasticsearch - Grafana Community
  3. elasticsearch - How to connect Elastic search 5.4 to tcp in java? - Stack Overflow
  4. Issue with elastic search 5.0.0 - NoClassDefFoundError: org/apache/logging/log4j/Logger - Elasticsearch - Discuss the Elastic Stack
  5. How to use Java API to build a nested query with filter query combination in 5.6.x? - Elasticsearch - Discuss the Elastic Stack
  6. Combining bool and range queries - Elasticsearch - Discuss the Elastic Stack
  7. Elasticsearch 范围查询
  8. es 多条件查询 or或 查询
  9. 使用JestClient操作ElasticSearch
  10. Jest - Elasticsearch Java Client | Baeldung
  11. elasticsearch - How to pass multiple node's address in jest (Elastic Search) - Stack Overflow
  12. how to write code for search in elasticsearch using jest client in java - Stack Overflow
  13. android - NoClassDefFoundError: Failed resolution of: Lorg/apache/http/conn/ssl/DefaultHostnameVerifier; - Stack Overflow

dailybird
1.1k 声望73 粉丝

I wanna.