ElasticSearch 7.3.0 (Springboot 2.3.11) is used in this experiment Elasticsearch is not compatible with ElasticSearch 7.3.0. Elasticsearch is not compatible with elasticSearch7.3.0.
Introduction of depend on
spring-boot-starter-data-elasticsearch
Copy the code
Adding a Configuration File
Spring: ElasticSearch: rest: # Comma-separated list of elasticSearch instances uris: http://ip:portCopy the code
Create a model class
package com.example.demo.elasticsearch.model;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Data
@Document(indexName = "operationlog")
public class OperationLogModel {
@Id
String id;
String idens;
String operationLog;
Long timestamp;
}
Copy the code
Create the Repository
public interface OperationLogRepository extends ElasticsearchRepository<OperationLogModel,String> {
}
Copy the code
Basically the same as JPA, you can refer to the following to meet their own query needs.
Create a service
Paging query
public Page<OperationLogModel> getAll(Pageable pageable) {
Page<OperationLogModel> iterable = operationLogRepository.findAll(pageable);
return iterable;
}
Copy the code
This code will enable paging queries, but remember to avoid pagesize>10000 because the default value of ElasticSearch is 10000. I get the following error when I test pagesize>10000
If your business needs to fetch more than 10000 records, you can use Scroll to fetch them.
Scroll retrieves all records
@Autowired
private ElasticsearchRestTemplate esTemplate;
public void scroll(String name){
IndexCoordinates index = IndexCoordinates.of("operation");
FieldSortBuilder fsb = SortBuilders.fieldSort("timestamp").order(SortOrder.DESC);
Query searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchQuery("name",name))
.withSort(fsb)
.withPageable(PageRequest.of(0, 10))
.build();
SearchScrollHits<OperationLogModel> scroll = esTemplate.searchScrollStart(1000, searchQuery, OperationLogModel.class, index);
String scrollId = scroll.getScrollId();
List<SearchHit<OperationLogModel>> sampleEntities = new ArrayList<>();
while (scroll.hasSearchHits()) {
sampleEntities.addAll(scroll.getSearchHits());
scrollId = scroll.getScrollId();
scroll = esTemplate.searchScrollContinue(scrollId, 1000, OperationLogModel.class,index);
}
System.out.println(sampleEntities.size());
}
Copy the code
The following is an example of Scroll provided on the official website. SearchQuery in this example has been removed from spring-boot-starter-data-ElasticSearch version 4.0.9. (So is this an official document error?) Just refer to the way I wrote above.