EsService.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package com.example.xiaoshiweixinback.service.common;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.elasticsearch._types.InlineScript;
  4. import co.elastic.clients.elasticsearch._types.Script;
  5. import co.elastic.clients.elasticsearch._types.query_dsl.Query;
  6. import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;
  7. import co.elastic.clients.elasticsearch.core.SearchRequest;
  8. import co.elastic.clients.elasticsearch.core.SearchResponse;
  9. import co.elastic.clients.elasticsearch.core.search.Hit;
  10. import co.elastic.clients.json.JsonData;
  11. import lombok.RequiredArgsConstructor;
  12. import org.springframework.context.annotation.Lazy;
  13. import org.springframework.stereotype.Service;
  14. import java.io.IOException;
  15. import java.util.ArrayList;
  16. import java.util.List;
  17. @Service
  18. @RequiredArgsConstructor(onConstructor_ = {@Lazy})
  19. public class EsService {
  20. private final ElasticsearchClient client;
  21. public List<Integer> getTenderList(List<Float> imageList) throws IOException {
  22. List<Integer> list = new ArrayList<>();
  23. SearchRequest.Builder builder = new SearchRequest.Builder();
  24. //设置查询索引
  25. builder.index("tender");
  26. String source = "cosineSimilarity(params.queryVector, 'my_vector') + 1.0";
  27. InlineScript inlineScript = InlineScript.of(i -> i.lang("painless").params("queryVector", JsonData.of(imageList)).source(source));
  28. Script script = Script.of(i -> i.inline(inlineScript));
  29. Query query = QueryBuilders.scriptScore(i -> i.script(script).query(org.springframework.data.elasticsearch.client.elc.QueryBuilders.matchAllQueryAsQuery()));
  30. builder.query(query);
  31. builder.size(10);
  32. SearchResponse<Integer> response = client.search(builder.build(), Integer.class);
  33. List<Hit<Integer>> hits = response.hits().hits();
  34. double scoreThreshold = 1.95;
  35. for (Hit<Integer> hit : hits) {
  36. Double score = hit.score();
  37. Integer tender = hit.source();
  38. if (score > scoreThreshold) {
  39. list.add(tender);
  40. }
  41. }
  42. return list;
  43. }
  44. }