77import org .springframework .ai .vectorstore .filter .Filter ;
88import org .springframework .stereotype .Service ;
99
10+ import java .util .ArrayList ;
1011import java .util .Collections ;
12+ import java .util .Comparator ;
1113import java .util .List ;
14+ import java .util .stream .Collectors ;
1215
1316@ Service
1417@ RequiredArgsConstructor
1518public class QdrantService {
1619
1720 private final VectorStore vectorStore ;
1821
19- public List <Document > searchDocument (String query , String key , String value , int topK ) {
22+ public List <Document > searchDocument (String query , String key , String value ) {
2023
21- SearchRequest caseSearchRequest = SearchRequest .builder ()
22- .query (query )
23- .topK (topK )
24+ SearchRequest findCaseNumberRequest = SearchRequest .builder ()
25+ .query (query ).topK (1 )
2426 .filterExpression (new Filter .Expression (Filter .ExpressionType .EQ , new Filter .Key (key ), new Filter .Value (value )))
2527 .build ();
26- List <Document > similarCaseDocuments = vectorStore .similaritySearch (caseSearchRequest );
27-
28- if (caseSearchRequest == null ) {
29- return Collections .singletonList (
30- Document .builder ()
31- .text ("더미" )
32- .metadata (key , value )
33- .score (0.0 )
34- .build ()
35- );
28+ List <Document > mostSimilarDocuments = vectorStore .similaritySearch (findCaseNumberRequest );
29+
30+
31+ if (mostSimilarDocuments .isEmpty ()) {
32+ return Collections .emptyList ();
33+ }
34+ String targetCaseNumber = (String ) mostSimilarDocuments .get (0 ).getMetadata ().get ("caseNumber" );
35+ if (targetCaseNumber == null ) {
36+ return mostSimilarDocuments ;
37+ }
38+
39+ SearchRequest fetchAllChunksRequest = SearchRequest .builder ()
40+ .query (query ).topK (100 )
41+ .filterExpression (new Filter .Expression (Filter .ExpressionType .EQ , new Filter .Key ("caseNumber" ), new Filter .Value (targetCaseNumber )))
42+ .build ();
43+ List <Document > allChunksOfCase = new ArrayList <>(vectorStore .similaritySearch (fetchAllChunksRequest ));
44+
45+ if (allChunksOfCase .isEmpty ()) {
46+ return Collections .emptyList ();
3647 }
3748
38- return similarCaseDocuments ;
49+ allChunksOfCase .sort (Comparator .comparingInt (doc ->
50+ ((Number ) doc .getMetadata ().get ("chunkIndex" )).intValue ()
51+ ));
52+
53+ String mergedContent = allChunksOfCase .stream ()
54+ .map (Document ::getText )
55+ .collect (Collectors .joining ("" ));
56+
57+ Document bestScoringDoc = allChunksOfCase .stream ()
58+ .max (Comparator .comparing (Document ::getScore ))
59+ .orElse (allChunksOfCase .get (0 ));
60+
61+ Document finalDocument = Document .builder ()
62+ .text (mergedContent )
63+ .metadata (bestScoringDoc .getMetadata ())
64+ .score (bestScoringDoc .getScore ())
65+ .build ();
66+
67+ return Collections .singletonList (finalDocument );
3968 }
4069
4170}
0 commit comments