Spring Data Elasticsearch

Spring Data's goal is to significantly reduce the boilerplate codes that are used to implement the data access layer. The Spring Data repository takes the domain class to manage its life cycle and provides basic functionalities such as CRUD, paging, and sorting. In order to use Spring Boot and Spring Data Elasticsearch, a new Spring Boot starter dependency is required to be added to pom.xml, as shown in the following code block: 

  <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

At the time of writing, the latest version of Spring Boot Starter Data Elasticsearch is 2.1.4, which supports Spring Data Elasticsearch 3.1.6 for Elasticsearch version 6.5.2. Interested users will need to wait for the new version to be released. Let's take an example using the contents of the cf_etf index as a domain class, which can be described as in the following code block. The @Document annotation represents a class that stores content as a document:

@Document(indexName="cf_etf", type="_doc")
public class Cf_etf {
@Id
private String symbol;
private String fund_name;
private int rating;
private String morningstar_category;
private String category;
private String family;
private String market_cap;
private String description;
private String exchange;
...
}

Next, we need to extend a repository interface, such as ElasticsearchRepository, which provides built-in support for CRUD, paging, sorting, and searching, among other functionalities. When Spring Data creates the corresponding repository implementation, it analyzes all the methods defined in the repository interface and attempts to automatically generate queries from the method name. It makes it easy for us to define new custom access methods. Let's create a Cf_etf repository corresponding to the Cf_etf domain class, with two additional methods:

public interface Cf_etfRepository extends ElasticsearchRepository<Cf_etf, String>{
Page<Cf_etf> findBySymbol(String symbol);

@Query("{"query":{"match_phrase":{"fund_name":{"query":"?0"}}}}")
Page<Cf_etf> matchFundNamePhraseQuery(String fund_name);
}

There are two ways to derive queries from the method names supported by the repository interface that we can see in the preceding code block:

  1. The method is derived directly from the method name (for example, findBySymbol). A list of supported keywords can be used to extend the usage of the queries. Let's give two in the following table. Interested users can refer to the documentation at https://docs.spring.io/spring-data/elasticsearch/docs/3.1.6.RELEASE/reference/html/ for more information:

Keyword

Method name

Query string

Is

findBySymbol

{"bool" : {"must" : {"field" : {"symbol" : "?"}}}}

And

findByCategoryAndRating

{"bool" : {"must" : [ {"field" : {"category" : "?"}}, {"field" : {"rating" : "?"}} ]}}

Other keywords are OrNotBetweenLessThanEqualGreaterThanEqualBeforeAfterLikeStartingWithEndingWithContainingInNotInNearTrueFalse, and OrderBy.
  1. Manually define the query at the method using the @Query annotation—for example, the matchFundNamePhraseQuery() method in the Cf_etfRepository interface.

Before we can use Cf_etfRepository to issue a query, we must activate the repository. Using JavaConfig, annotation-based configuration is one of the easiest ways to achieve this. Let's take a look at the following code block:

@Configuration
@EnableAutoConfiguration(exclude={ElasticsearchDataAutoConfiguration.class})
@EnableElasticsearchRepositories(basePackages = "com.example.client.restclient.repository")
public class SpringDataClientConfig {
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.transport-client-port}")
private int port;

@Bean
public Client client() throws Exception {
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY);
client.addTransportAddress(new TransportAddress(InetAddress.getByName(host), port));
return client;
}
@Bean
public ElasticsearchOperations elasticsearchTemplate() throws Exception {
return new ElasticsearchTemplate(client());
}
}

We will notice that Spring Data Elasticsearch uses a transport client to create a communicate tunnel to talk to the server. Since Elasticsearch intends to deprecate the transport client in version 7.0, and remove it with 8.0, the Spring Data project team is working on a smoother migration by using a REST client. Interested users can check progress at the Spring Data Elasticsearch Jira issue DATES-495, available at https://jira.spring.io/browse/DATAES-495). We have completed the discussion with all the materials we have prepared for Java programming with Elasticsearch. We'll conclude this chapter in the following section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.49.190