整合过程见上一篇文章
springboot整合elasticsearch8文章来源地址https://www.toymoban.com/news/detail-598235.html
1.es8多条件组合查询
@Slf4j
@RestController
@RequestMapping("/elastic")
public class ElasticSearchTestController {
@Autowired
private ElasticsearchClient client;
@GetMapping("/user")
public List getUser() throws IOException {
List<User> userList = new ArrayList<>();
String name = "张三";
// 构建查询条件
List<Query> queryList = new ArrayList<>();
// MatchPhraseQuery
Query byName = MatchPhraseQuery.of(m -> m
.field("name")
.query(name)
)._toQuery();
// RangeQuery
Query byAge1 = RangeQuery.of(r -> r
.field("age")
.gte(JsonData.of(10))
)._toQuery();
Query byAge2 = RangeQuery.of(r -> r
.field("age")
.lte(JsonData.of(13))
)._toQuery();
// TermsQuery
List<FieldValue> ls = new ArrayList<>();
ls.add(FieldValue.of("男"));
ls.add(FieldValue.of("女"));
Query termsQuery = TermsQuery.of(t ->t.field("sex").terms(terms ->terms.value(ls)))._toQuery();
queryList.add(byName);
queryList.add(byAge1);
queryList.add(byAge2);
queryList.add(termsQuery);
String[] sources = new String[]{"name", "age"};
SearchResponse<User> response = client.search(s -> s
.index("user").query(q -> q.bool(b -> b.must(queryList)))
.sort(sort -> sort.field(f -> f.field("age").order(SortOrder.Asc))) //排序
.source(sc -> sc //查询字段过滤
.filter(f -> f
.includes(Arrays.asList(sources))
)
)
.from(0) //分页
.size(10),
User.class
);
List<Hit<User>> hits = response.hits().hits();
for (Hit<User> hit: hits) {
userList.add(hit.source());
}
return userList;
}
}
2.使用scroll进行大数据量查询
...
// 第一次查询
SearchResponse<User> response = client.search(s -> s
.index("user")
.query(q -> q.bool(b -> b.must(queryList)))
.size(5000)
.scroll(t ->t.time("5m")), //开启scroll
User.class
);
List<Hit<User>> hits = response.hits().hits();
for (Hit<User> hit: hits) {
userList.add(hit.source());
}
String scrollId = response.scrollId();
List<String> strings = new ArrayList<>();
strings.add(scrollId);
ScrollResponse<User> search = null;
do {
String scrollIdTemp = scrollId;
log.info(scrollIdTemp);
search = client.scroll(s->s.scrollId(scrollIdTemp).scroll(t->t.time("5m")),User.class);
for (Hit<User> hit : search.hits().hits()) {
userList.add(hit.source());
}
scrollId = search.scrollId();
strings.add(scrollId);
}while(!search.hits().hits().isEmpty());
// 清除scrollId
client.clearScroll(c->c.scrollId(strings));
...
文章来源:https://www.toymoban.com/news/detail-598235.html
到了这里,关于springboot整合elasticsearch8组合条件查询的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!