/
DocumentVSRepositoryBean.java
153 lines (124 loc) · 5.71 KB
/
DocumentVSRepositoryBean.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
/**
* Copyright 2023 Sven Loesekann
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.xxx.aidoclibchat.adapter.repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
import org.postgresql.util.PGobject;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.vectorstore.PgVectorStore;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.filter.Filter;
import org.springframework.ai.vectorstore.filter.Filter.ExpressionType;
import org.springframework.ai.vectorstore.filter.Filter.Key;
import org.springframework.ai.vectorstore.filter.Filter.Value;
import org.springframework.ai.vectorstore.filter.FilterExpressionConverter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pgvector.PGvector;
import ch.xxx.aidoclibchat.domain.common.MetaData;
import ch.xxx.aidoclibchat.domain.common.MetaData.DataType;
import ch.xxx.aidoclibchat.domain.model.entity.DocumentVsRepository;
@Repository
public class DocumentVSRepositoryBean implements DocumentVsRepository {
private final String vectorTableName;
private final VectorStore vectorStore;
private final JdbcTemplate jdbcTemplate;
private final ObjectMapper objectMapper;
private final FilterExpressionConverter filterExpressionConverter;
public DocumentVSRepositoryBean(JdbcTemplate jdbcTemplate, EmbeddingClient embeddingClient, ObjectMapper objectMapper) {
this.jdbcTemplate = jdbcTemplate;
this.objectMapper = objectMapper;
this.vectorStore = new PgVectorStore(jdbcTemplate, embeddingClient);
this.filterExpressionConverter = ((PgVectorStore) this.vectorStore).filterExpressionConverter;
this.vectorTableName = PgVectorStore.VECTOR_TABLE_NAME;
}
@Override
public void add(List<Document> documents) {
this.vectorStore.add(documents);
}
@Override
public List<Document> retrieve(String query, DataType dataType, int k, double threshold) {
return this.vectorStore
.similaritySearch(SearchRequest
.query(query).withFilterExpression(new Filter.Expression(ExpressionType.EQ,
new Key(MetaData.DATATYPE), new Value(dataType.toString())))
.withTopK(k).withSimilarityThreshold(threshold));
}
@Override
public List<Document> retrieve(String query, DataType dataType, int k) {
return this.vectorStore.similaritySearch(SearchRequest.query(query).withFilterExpression(
new Filter.Expression(ExpressionType.EQ, new Key(MetaData.DATATYPE), new Value(dataType.toString())))
.withTopK(k));
}
@Override
public List<Document> retrieve(String query, DataType dataType) {
return this.vectorStore.similaritySearch(SearchRequest.query(query).withFilterExpression(
new Filter.Expression(ExpressionType.EQ, new Key(MetaData.DATATYPE), new Value(dataType.toString()))));
}
@Override
public List<Document> findAllTableDocuments() {
String nativeFilterExpression = this.filterExpressionConverter.convertExpression(new Filter.Expression(ExpressionType.NE,
new Key(MetaData.DATATYPE), new Value(DataType.DOCUMENT.toString())));
String jsonPathFilter = " WHERE metadata::jsonb @@ '" + nativeFilterExpression + "'::jsonpath ";
return this.jdbcTemplate.query(
String.format("SELECT * FROM %s %s LIMIT ? ", this.vectorTableName, jsonPathFilter),
new DocumentRowMapper(this.objectMapper), 100000);
}
@Override
public void deleteByIds(List<String> ids) {
this.vectorStore.delete(ids);
}
private static class DocumentRowMapper implements RowMapper<Document> {
private static final String COLUMN_EMBEDDING = "embedding";
private static final String COLUMN_METADATA = "metadata";
private static final String COLUMN_ID = "id";
private static final String COLUMN_CONTENT = "content";
private ObjectMapper objectMapper;
public DocumentRowMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public Document mapRow(ResultSet rs, int rowNum) throws SQLException {
String id = rs.getString(COLUMN_ID);
String content = rs.getString(COLUMN_CONTENT);
PGobject pgMetadata = rs.getObject(COLUMN_METADATA, PGobject.class);
PGobject embedding = rs.getObject(COLUMN_EMBEDDING, PGobject.class);
Map<String, Object> metadata = toMap(pgMetadata);
Document document = new Document(id, content, metadata);
document.setEmbedding(toDoubleList(embedding));
return document;
}
private List<Double> toDoubleList(PGobject embedding) throws SQLException {
float[] floatArray = new PGvector(embedding.getValue()).toArray();
return IntStream.range(0, floatArray.length).mapToDouble(i -> floatArray[i]).boxed().toList();
}
@SuppressWarnings("unchecked")
private Map<String, Object> toMap(PGobject pgObject) {
String source = pgObject.getValue();
try {
return (Map<String, Object>) objectMapper.readValue(source, Map.class);
}
catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
}