dawdler-server-plug-es
Module Introduction
Provides injection of EsOperator on the dawdler-server side.
1. Adding the Dependency to pom
<groupId>club.dawdler</groupId>
<artifactId>dawdler-server-plug-es</artifactId>
2. Usage
Simply use the @EsInjector annotation to mark a global variable as an EsOperator-typed variable.
public class ProductServiceImpl implements ProductService {
@EsInjector("myEs")// myEs is the name of the configuration file, without the properties suffix
EsOperator esOperator;
public List<Product> productSearch(String userId) throws IOException {
List<Product> list = termQuery("product", "name", "电冰箱", "addTime", 0, 10, false, Product.class);
return list;
}
public <T> List<T> termQuery(
String indexName,
String searchField,
String searchText,
String sortedField,
int fromIndex,
int pageSize,
boolean isDesc,
Class<T> clazz)
throws IOException {
SearchResponse<T> response = esOperator.search(
s -> s.index(indexName)
.query(q -> q.match(t -> t.field(searchField).query(searchText)))
// Paged query: start from page fromIndex and retrieve pageSize documents
.from(fromIndex)
.size(pageSize)
// Sort in descending order by the field to sort on
.sort(f -> f.field(o -> o.field(sortedField).order(isDesc ? SortOrder.Desc : SortOrder.Asc))),
clazz);
return getSources(response);
}
private <T> List<T> getSources(SearchResponse<T> response) {
List<T> result = new ArrayList<>();
for (Hit<T> hit : getHitList(response)) {
result.add(hit.source());
}
return result;
}
private <T> List<Hit<T>> getHitList(SearchResponse<T> response) {
List<Hit<T>> hitList = response.hits().hits();
if (hitList == null || hitList.isEmpty()) {
return new ArrayList<>();
}
return hitList;
}
}