Просмотр исходного кода

修复查询不准确,把匹配度是最高分的50%一下的过滤掉

Jacky Wong лет назад: 4
Родитель
Сommit
9efc1e476a

+ 25 - 1
search-service-quiz/src/main/java/com/liangjian/search/service/impl/QAProblemService.java

@@ -13,12 +13,18 @@ import com.liangjian.search.service.IQAProblemService;
 import com.liangjian.search.service.IQAProblemTagService;
 import com.liangjian.search.util.Tuple;
 import com.liangjian.search.util.Tuple2;
+import org.elasticsearch.action.search.SearchRequest;
+import org.elasticsearch.action.search.SearchResponse;
+import org.elasticsearch.client.RequestOptions;
 import org.elasticsearch.index.query.BoolQueryBuilder;
 import org.elasticsearch.search.builder.SearchSourceBuilder;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.domain.Page;
 import org.springframework.data.domain.PageRequest;
 import org.springframework.data.domain.Pageable;
+import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
+import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
+import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
 import org.springframework.stereotype.Service;
 
 import java.util.List;
@@ -34,6 +40,8 @@ public class QAProblemService extends ServiceImpl<QAProblemMapper,QAProblem> imp
     private QAProblemEsRepository qaProblemEsRepository;
     @Autowired
     private IQAProblemTagService iqaProblemTagService;
+    @Autowired
+    private ElasticsearchRestTemplate elasticsearchRestTemplate;
 
     @Override
     public List<QAProblem> getWrappedProblem(Long id, Integer offset, Integer limit) {
@@ -54,7 +62,23 @@ public class QAProblemService extends ServiceImpl<QAProblemMapper,QAProblem> imp
                         should(matchQuery("describe.pinyin", keyword))
                 );
         SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(queryBuilder);
-        return qaProblemEsRepository.search(sourceBuilder.query(),pageable);
+        SearchRequest request = new SearchRequest("qa_problem").source(sourceBuilder);
+        try {
+            SearchResponse response = elasticsearchRestTemplate.getClient().search(request, RequestOptions.DEFAULT);
+            Float maxScore = response.getHits().getMaxScore();
+            Double mustMinScore = (maxScore * 0.5);
+
+            var secondSearch = new NativeSearchQuery(queryBuilder);
+            secondSearch.setMinScore(mustMinScore.floatValue());
+            secondSearch.setPageable(pageable);
+            var pager = elasticsearchRestTemplate.queryForPage(secondSearch,QAProblemEs.class);
+            return pager;
+        } catch (Exception ex) {
+           ex.printStackTrace();
+           var pager = qaProblemEsRepository.search(sourceBuilder.query(),pageable);
+           return pager;
+        }
+        //return qaProblemEsRepository.search(sourceBuilder.query(),pageable);
     }
 
     @Override