24 Ekim 2021 Pazar

SpringData ElasticSearch RestHighLevelClient Sınıfı - Kullanmayın

Giriş
Açıklaması şöyle
There are two ways to do operations on elastic search using spring boot.
1. By using ElasticsearchRestTemplate: This we should use when we want to create more complex queries.
2. By Using Repositories: This is very simple and it has all the methods defined and internally it creates elastic-based queries.
Yani eğer ElasticsearchRepository kullanıyorsak bu sınıfı direkt kullanmaya gerek yok. Açıklaması şöyle
The Java High-Level REST Client works on top of the Java Low-Level REST client. Its main goal is to expose API specific methods, that accept request objects as an argument and return response objects, so that request marshalling and response un-marshalling is handled by the client itself.

Each API can be called synchronously or asynchronously. The synchronous methods return a response object, while the asynchronous methods, whose names end with the async suffix, require a listener argument that is notified (on the thread pool managed by the low-level client) once a response or an error is received.

The Java High-Level REST Client depends on the Elasticsearch core project. It accepts the same request arguments as the TransportClient and returns the same response objects.
Aslında bu sınıfı direk kullanmaya da gerek yok. Eğer ElasticsearchRestTemplate kullanacaksak şu açıklamayı bilmek lazım. Açıklaması şöyle
ElasticSearchRestTemplate is built on the top of RestHighLevelClient. You can think of it as a Spring wrapper over RestHighLevelClient.
Maven
Şu satırı dahil ederiz
<dependency>
  <groupId>org.elasticsearch.client</groupId>
  <artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
constructor
Örnek
Şöyle yaparız
@Bean
public RestHighLevelClient client() { RestHighLevelClient client = new RestHighLevelClient(new HttpHost("server",9200,"http")) .setMaxRetryTimeoutMillis(12000); }
Örnek
Elimizde şöyle bir dosya olsun
spring.data.elasticsearch.cluster-nodes=${ELASTICSEARCH_HOST:localhost:9200}
Şöyle yaparız
@Configuration
public class ElasticSearchConfig {
  @Value("${spring.data.elasticsearch.cluster-nodes}")
  String elasticHost;
  
  @Bean
  public RestHighLevelClient client() {
    return new RestHighLevelClient(RestClient.builder(HttpHost.create(elasticHost)));
  }
}
bulk metodu
Örnek
Şöylee yaparız
@Override
public BulkResponse saveAll(List<Product> products) throws IOException {

  BulkRequest bulkRequest = Requests.bulkRequest();
  products.forEach(product -> {
    try {
      IndexRequest indexRequest = Requests.indexRequest(INDEX_NAME)
        .source(convertProductToMap(product));
      bulkRequest.add(indexRequest);
    } catch (JsonProcessingException e) {
      // log error
    }
  });

  RequestOptions options = RequestOptions.DEFAULT;
  return restHighLevelClient.bulk(bulkRequest, options);
}
delete metodu
Veri tabanındaki kaydı siler
Bir örnek burada

index metodu
Veri tabanında yeni bir kayıt oluşturur
Örnek
Şöyle yaparız
@Override
public IndexResponse save(Product product) throws IOException {

  IndexRequest indexRequest = Requests.indexRequest(INDEX_NAME)
            .id(product.getId().toString())
            .source(convertProductToMap(product));

  RequestOptions options = RequestOptions.DEFAULT;
  return restHighLevelClient.index(indexRequest, options);
}

@Autowired
ObjectMapper objectMapper;
private Map<String, Object> convertProductToMap(Product product)
throws JsonProcessingException {
    String json = objectMapper.writeValueAsString(product);
    return objectMapper.readValue(json, Map.class);
}
Açıklaması şöyle
Pay attention to convertProductToMap() function, it will convert our Product object to a Map<String, Object>.
...
I am using Gson to encode it to JSON, then decode it to a Map class.
update metodu
Veri tabanındaki kaydı günceller

Bir örnek burada

search metodu
Bir örnek burada









Hiç yorum yok:

Yorum Gönder