1. Spring Data Elasticsearch
Spring Data Elasticsearch is a subproject of the Spring Data project that provides Elasticsearch integration with Spring. Elasticsearch provides Spring Data Repository style for Elasticsearch client development.
2. Some personal views
Elasticsearch was specifically integrated into Spring Boot as requested by fans. The idea was to integrate into kono scaffolding, but on second thought this was not a good fit. The general search proposal works as a standalone platform, small companies as a standalone service, and large companies as a search hub. Although Elasticsearch does have a search capability, most of the time we don’t write directly like a normal relational database, but instead synchronize or preheat data.
The specific architecture is not discussed in this paper. There are specific solutions in the official CSDN blog of ES. This article assumes that you already have your Elasticsearch cluster set up.
2. Version mapping
The versions of related projects are as follows:
Spring Data Release Train | Spring Data Elasticsearch | Elasticsearch | Spring Boot |
---|---|---|---|
Neumann | X 4.0. | 7.6.2 | X 2.3. |
Moore | X 3.2. | 6.8.6 | X 2.2. |
Lovelace | X 3.1. | 6.2.2 | X 2.1. |
Kay | X 3.0. | 5.5.0 | X 2.0. |
Ingalls | X 2.1. | 2.4.0 | X 1.5. |
Based on my usual practice, I chose Elasticsearch 7.6.2 and Spring Boot 2.3.3 as version benchmarks for integration.
3. Importing and configuring dependencies
To integrate Elasticsearch, you only need to introduce the following dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
Copy the code
There are two types of configuration. One is traditional Restful:
spring:
elasticsearch:
rest:
# comma-separated list of Elasticsearch instances to use
uris: http://localhost:9200
# link timeout
connection-timeout:
Read timeout
read-timeout:
# ES user name
username:
# ES password
password:
Copy the code
If you use the default configuration, you can configure nothing, including URIs.
Another oriented equation:
spring:
data:
elasticsearch:
client:
# Reactant-dependent configuration
reactive:
# endpoint
endpoints:
connection-timeout:
max-in-memory-size:
socket-timeout:
use-ssl:
username:
password:
Copy the code
The Spring Webflux reaction framework is used here. Personally, I prefer it, but as the current mainstream, I still choose the first one.
Ensure that spring. The data. Elasticsearch. Repositories. Enabled = true, otherwise unable to use the spring data Repository model.
4. Operating
This demo is for traditional Restful, and there are two styles. Suppose we write to the Blog:
{
"blogId": "132435553"."blogTitle": "Scaffold integrated ElasticSearch"."author": "felord"."content": "Object Storage Service, also known as Object Storage Service, is a method to solve and process discrete units. It provides object-based data Storage services based on distributed systems. It is extensible, manageable, and low-cost, supports central and edge Storage, and achieves elastic scaling of Storage requirements. It applies to various scenarios of maritime data management. The concept of \n\n is really hard to understand. Simple say something I know, normally we are documents address/User/felord/video/XXX. Mp4 directory tree structure, system to find the User first, and then find has been cascaded down to the target, it is a structured way of storage. Object storage is different. All files are stored in a specific pool, but the file carries its own meta-information through which to retrieve the file.."url": "https://felord.cn/my-spring-boot-day7.html"."publishedTime": "2020-08-30T22:17:40"
}
Copy the code
The corresponding POJO object is:
/ * * *@author felord.cn
* @since2020/8/30 16:10 * /
@Document(indexName = "blogs")
@Data
public class Blog {
@Id
private String blogId;
private String blogTitle;
private String author;
private String content;
private String url;
@Field(type = FieldType.Date,format = DateFormat.date_hour_minute_second)
private LocalDateTime publishedTime;
}
Copy the code
@Document
Used to mark a document object, containing meta information about the document, number of index copies, number of shards.@Id
The identifier of the document.@Field
Some meta-information configuration for document fields, type, name, word divider, and so on.
There are three main ones, as well as other annotations that are not covered here.
4.1 ElasticsearchRestTemplate
RedisTemplate believe you already not strange, in the same way, the Spring Data Elasticsearch provides ElasticsearchRestTemplate to Elasticsearch operation, add and delete everything. Complex Criteria queries are demonstrated here.
Query from the Blogs index for documents whose blogId is 132435553 and contains the title of an Elastic term, and also search for term highlighting
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
@Test
void testTemplate(a) {
// Structure condition
Criteria criteria = Criteria.where(new SimpleField("blogId"))
.is("132435553")
.and(new SimpleField("blogTitle"))
.contains("elastic");
CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
/ / highlight
HighlightBuilder blogTitle = SearchSourceBuilder.highlight().field("blogTitle");
HighlightQuery highlightQuery = new HighlightQuery(blogTitle);
criteriaQuery.setHighlightQuery(highlightQuery);
SearchHits<Blog> blogSearchHits = elasticsearchRestTemplate.search(criteriaQuery, Blog.class);
blogSearchHits.getSearchHits().forEach(System.out::println);
}
Copy the code
4.2 the Spring Data Repository
The core interface of Spring Data Repository is Repository. This interface takes the domain class (like the Blog above) and the ID type of the domain class as parameters. The main purpose of this interface is to let you know the type of interface that inherits this class. CrudRepository provides some common add, delete, or modify lookup methods for managed entity classes. Elasticsearch provides various special interfaces for Elasticsearch:
The Repository schema provides a way to conditionally construct queries using method names.
The advantage of this approach is that it is semantic, but the disadvantage is that method names can be very long. For the example in 4.1, we can simplify it as:
/ * * *@author felord.cn
* @sinceOrder 2020/8/30 arrive * /
public interface BlogRepository extends ElasticsearchRepository<Blog.String> {
@Highlight(fields = { @HighlightField(name = "blogTitle") })
List<SearchHit<Blog>> searchBlogByBlogIdAndBlogTitleContains(String blogId, String titleContains);
}
Copy the code
The other is to annotate, using the @query annotation. For example, if we were to Query against a blogId, we could write:
@Query("{\"match\": {\"blogId\": \"? 0 \ "}} ")
// @Query("{\"match\": {\"blogId\":{\"query\": \"? 0 \ "}}} ")
Blog searchById(String blogId);
Copy the code
This advantage is more flexible, but also more casual and simple writing; The disadvantage is that you need to be familiar with Spring Data Elasticsearch and the query syntax of Elasticsearch.
conclusion
Elasticsearch Spring Data Search Spring Data Elasticsearch Spring Data Elasticsearch Spring Data Elasticsearch makes it very easy to search for Elasticsearch. If you have any problems with it, please leave a comment on it.
Follow our public id: Felordcn for more information
Personal blog: https://felord.cn