-
Notifications
You must be signed in to change notification settings - Fork 2k
/
neo4j_vector.ts
1141 lines (969 loc) Β· 31.7 KB
/
neo4j_vector.ts
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import neo4j from "neo4j-driver";
import * as uuid from "uuid";
import type { EmbeddingsInterface } from "@langchain/core/embeddings";
import { VectorStore } from "@langchain/core/vectorstores";
import { Document } from "@langchain/core/documents";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Any = any;
export type SearchType = "vector" | "hybrid";
export type IndexType = "NODE" | "RELATIONSHIP";
export type DistanceStrategy = "euclidean" | "cosine";
export type Metadata = Record<string, unknown>;
interface Neo4jVectorStoreArgs {
url: string;
username: string;
password: string;
database?: string;
preDeleteCollection?: boolean;
textNodeProperty?: string;
textNodeProperties?: string[];
embeddingNodeProperty?: string;
keywordIndexName?: string;
indexName?: string;
searchType?: SearchType;
indexType?: IndexType;
retrievalQuery?: string;
nodeLabel?: string;
createIdIndex?: boolean;
}
const DEFAULT_SEARCH_TYPE = "vector";
const DEFAULT_INDEX_TYPE = "NODE";
const DEFAULT_DISTANCE_STRATEGY = "cosine";
const DEFAULT_NODE_EMBEDDING_PROPERTY = "embedding";
/**
* @security *Security note*: Make sure that the database connection uses credentials
* that are narrowly-scoped to only include necessary permissions.
* Failure to do so may result in data corruption or loss, since the calling
* code may attempt commands that would result in deletion, mutation
* of data if appropriately prompted or reading sensitive data if such
* data is present in the database.
* The best way to guard against such negative outcomes is to (as appropriate)
* limit the permissions granted to the credentials used with this tool.
* For example, creating read only users for the database is a good way to
* ensure that the calling code cannot mutate or delete data.
*
* @link See https://js.langchain.com/docs/security for more information.
*/
export class Neo4jVectorStore extends VectorStore {
private driver: neo4j.Driver;
private database: string;
private preDeleteCollection: boolean;
private nodeLabel: string;
private embeddingNodeProperty: string;
private embeddingDimension: number;
private textNodeProperty: string;
private keywordIndexName: string;
private indexName: string;
private retrievalQuery: string;
private searchType: SearchType;
private indexType: IndexType;
private distanceStrategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY;
private supportMetadataFilter = true;
private isEnterprise = false;
_vectorstoreType(): string {
return "neo4jvector";
}
constructor(embeddings: EmbeddingsInterface, config: Neo4jVectorStoreArgs) {
super(embeddings, config);
}
static async initialize(
embeddings: EmbeddingsInterface,
config: Neo4jVectorStoreArgs
) {
const store = new Neo4jVectorStore(embeddings, config);
await store._initializeDriver(config);
await store._verifyConnectivity();
const {
preDeleteCollection = false,
nodeLabel = "Chunk",
textNodeProperty = "text",
embeddingNodeProperty = DEFAULT_NODE_EMBEDDING_PROPERTY,
keywordIndexName = "keyword",
indexName = "vector",
retrievalQuery = "",
searchType = DEFAULT_SEARCH_TYPE,
indexType = DEFAULT_INDEX_TYPE,
} = config;
store.embeddingDimension = (await embeddings.embedQuery("foo")).length;
store.preDeleteCollection = preDeleteCollection;
store.nodeLabel = nodeLabel;
store.textNodeProperty = textNodeProperty;
store.embeddingNodeProperty = embeddingNodeProperty;
store.keywordIndexName = keywordIndexName;
store.indexName = indexName;
store.retrievalQuery = retrievalQuery;
store.searchType = searchType;
store.indexType = indexType;
if (store.preDeleteCollection) {
await store._dropIndex();
}
return store;
}
async _initializeDriver({
url,
username,
password,
database = "neo4j",
}: Neo4jVectorStoreArgs) {
try {
this.driver = neo4j.driver(url, neo4j.auth.basic(username, password));
this.database = database;
} catch (error) {
throw new Error(
"Could not create a Neo4j driver instance. Please check the connection details."
);
}
}
async _verifyConnectivity() {
await this.driver.verifyAuthentication();
}
async _verifyVersion() {
try {
const data = await this.query("CALL dbms.components()");
const versionString: string = data[0].versions[0];
const targetVersion = [5, 11, 0];
let version: number[];
if (versionString.includes("aura")) {
// Get the 'x.y.z' part before '-aura'
const baseVersion = versionString.split("-")[0];
version = baseVersion.split(".").map(Number);
version.push(0);
} else {
version = versionString.split(".").map(Number);
}
if (isVersionLessThan(version, targetVersion)) {
throw new Error(
"Version index is only supported in Neo4j version 5.11 or greater"
);
}
const metadataTargetVersion = [5, 18, 0];
if (isVersionLessThan(version, metadataTargetVersion)) {
this.supportMetadataFilter = false;
}
this.isEnterprise = data[0].edition === "enterprise";
} catch (error) {
console.error("Database version check failed:", error);
}
}
async close() {
await this.driver.close();
}
async _dropIndex() {
try {
await this.query(`
MATCH (n:\`${this.nodeLabel}\`)
CALL {
WITH n
DETACH DELETE n
}
IN TRANSACTIONS OF 10000 ROWS;
`);
await this.query(`DROP INDEX ${this.indexName}`);
} catch (error) {
console.error("An error occurred while dropping the index:", error);
}
}
async query(query: string, params: Any = {}): Promise<Any[]> {
const session = this.driver.session({ database: this.database });
const result = await session.run(query, params);
return toObjects(result.records);
}
static async fromTexts(
texts: string[],
metadatas: Any,
embeddings: EmbeddingsInterface,
config: Neo4jVectorStoreArgs
): Promise<Neo4jVectorStore> {
const docs = [];
for (let i = 0; i < texts.length; i += 1) {
const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;
const newDoc = new Document({
pageContent: texts[i],
metadata,
});
docs.push(newDoc);
}
return Neo4jVectorStore.fromDocuments(docs, embeddings, config);
}
static async fromDocuments(
docs: Document[],
embeddings: EmbeddingsInterface,
config: Neo4jVectorStoreArgs
): Promise<Neo4jVectorStore> {
const {
searchType = DEFAULT_SEARCH_TYPE,
createIdIndex = true,
textNodeProperties = [],
} = config;
const store = await this.initialize(embeddings, config);
const embeddingDimension = await store.retrieveExistingIndex();
if (!embeddingDimension) {
await store.createNewIndex();
} else if (store.embeddingDimension !== embeddingDimension) {
throw new Error(
`Index with name "${store.indexName}" already exists. The provided embedding function and vector index dimensions do not match.
Embedding function dimension: ${store.embeddingDimension}
Vector index dimension: ${embeddingDimension}`
);
}
if (searchType === "hybrid") {
const ftsNodeLabel = await store.retrieveExistingFtsIndex();
if (!ftsNodeLabel) {
await store.createNewKeywordIndex(textNodeProperties);
} else {
if (ftsNodeLabel !== store.nodeLabel) {
throw Error(
"Vector and keyword index don't index the same node label"
);
}
}
}
if (createIdIndex) {
await store.query(
`CREATE CONSTRAINT IF NOT EXISTS FOR (n:${store.nodeLabel}) REQUIRE n.id IS UNIQUE;`
);
}
await store.addDocuments(docs);
return store;
}
static async fromExistingIndex(
embeddings: EmbeddingsInterface,
config: Neo4jVectorStoreArgs
) {
const { searchType = DEFAULT_SEARCH_TYPE, keywordIndexName = "keyword" } =
config;
if (searchType === "hybrid" && !keywordIndexName) {
throw Error(
"keyword_index name has to be specified when using hybrid search option"
);
}
const store = await this.initialize(embeddings, config);
const embeddingDimension = await store.retrieveExistingIndex();
if (!embeddingDimension) {
throw Error(
"The specified vector index name does not exist. Make sure to check if you spelled it correctly"
);
}
if (store.embeddingDimension !== embeddingDimension) {
throw new Error(
`The provided embedding function and vector index dimensions do not match.
Embedding function dimension: ${store.embeddingDimension}
Vector index dimension: ${embeddingDimension}`
);
}
if (searchType === "hybrid") {
const ftsNodeLabel = await store.retrieveExistingFtsIndex();
if (!ftsNodeLabel) {
throw Error(
"The specified keyword index name does not exist. Make sure to check if you spelled it correctly"
);
} else {
if (ftsNodeLabel !== store.nodeLabel) {
throw Error(
"Vector and keyword index don't index the same node label"
);
}
}
}
return store;
}
static async fromExistingGraph(
embeddings: EmbeddingsInterface,
config: Neo4jVectorStoreArgs
) {
const {
textNodeProperties = [],
embeddingNodeProperty = DEFAULT_NODE_EMBEDDING_PROPERTY,
searchType = DEFAULT_SEARCH_TYPE,
retrievalQuery = "",
nodeLabel,
} = config;
let _retrievalQuery = retrievalQuery;
if (textNodeProperties.length === 0) {
throw Error(
"Parameter `text_node_properties` must not be an empty array"
);
}
if (!retrievalQuery) {
_retrievalQuery = `
RETURN reduce(str='', k IN ${JSON.stringify(textNodeProperties)} |
str + '\\n' + k + ': ' + coalesce(node[k], '')) AS text,
node {.*, \`${embeddingNodeProperty}\`: Null, id: Null, ${textNodeProperties
.map((prop) => `\`${prop}\`: Null`)
.join(", ")} } AS metadata, score
`;
}
const store = await this.initialize(embeddings, {
...config,
retrievalQuery: _retrievalQuery,
});
const embeddingDimension = await store.retrieveExistingIndex();
if (!embeddingDimension) {
await store.createNewIndex();
} else if (store.embeddingDimension !== embeddingDimension) {
throw new Error(
`Index with name ${store.indexName} already exists. The provided embedding function and vector index dimensions do not match.\nEmbedding function dimension: ${store.embeddingDimension}\nVector index dimension: ${embeddingDimension}`
);
}
if (searchType === "hybrid") {
const ftsNodeLabel = await store.retrieveExistingFtsIndex(
textNodeProperties
);
if (!ftsNodeLabel) {
await store.createNewKeywordIndex(textNodeProperties);
} else {
if (ftsNodeLabel !== store.nodeLabel) {
throw Error(
"Vector and keyword index don't index the same node label"
);
}
}
}
// eslint-disable-next-line no-constant-condition
while (true) {
const fetchQuery = `
MATCH (n:\`${nodeLabel}\`)
WHERE n.${embeddingNodeProperty} IS null
AND any(k in $props WHERE n[k] IS NOT null)
RETURN elementId(n) AS id, reduce(str='', k IN $props |
str + '\\n' + k + ':' + coalesce(n[k], '')) AS text
LIMIT 1000
`;
const data = await store.query(fetchQuery, { props: textNodeProperties });
if (!data) {
continue;
}
const textEmbeddings = await embeddings.embedDocuments(
data.map((el) => el.text)
);
const params = {
data: data.map((el, index) => ({
id: el.id,
embedding: textEmbeddings[index],
})),
};
await store.query(
`
UNWIND $data AS row
MATCH (n:\`${nodeLabel}\`)
WHERE elementId(n) = row.id
CALL db.create.setVectorProperty(n, '${embeddingNodeProperty}', row.embedding)
YIELD node RETURN count(*)
`,
params
);
if (data.length < 1000) {
break;
}
}
return store;
}
async createNewIndex(): Promise<void> {
const indexQuery = `
CALL db.index.vector.createNodeIndex(
$index_name,
$node_label,
$embedding_node_property,
toInteger($embedding_dimension),
$similarity_metric
)
`;
const parameters = {
index_name: this.indexName,
node_label: this.nodeLabel,
embedding_node_property: this.embeddingNodeProperty,
embedding_dimension: this.embeddingDimension,
similarity_metric: this.distanceStrategy,
};
await this.query(indexQuery, parameters);
}
async retrieveExistingIndex() {
let indexInformation = await this.query(
`
SHOW INDEXES YIELD name, type, labelsOrTypes, properties, options
WHERE type = 'VECTOR' AND (name = $index_name
OR (labelsOrTypes[0] = $node_label AND
properties[0] = $embedding_node_property))
RETURN name, labelsOrTypes, properties, options
`,
{
index_name: this.indexName,
node_label: this.nodeLabel,
embedding_node_property: this.embeddingNodeProperty,
}
);
if (indexInformation) {
indexInformation = this.sortByIndexName(indexInformation, this.indexName);
try {
const [index] = indexInformation;
const [labelOrType] = index.labelsOrTypes;
const [property] = index.properties;
this.indexName = index.name;
this.nodeLabel = labelOrType;
this.embeddingNodeProperty = property;
const embeddingDimension =
index.options.indexConfig["vector.dimensions"];
return Number(embeddingDimension);
} catch (error) {
return null;
}
}
return null;
}
async retrieveExistingFtsIndex(
textNodeProperties: string[] = []
): Promise<string | null> {
const indexInformation = await this.query(
`
SHOW INDEXES YIELD name, type, labelsOrTypes, properties, options
WHERE type = 'FULLTEXT' AND (name = $keyword_index_name
OR (labelsOrTypes = [$node_label] AND
properties = $text_node_property))
RETURN name, labelsOrTypes, properties, options
`,
{
keyword_index_name: this.keywordIndexName,
node_label: this.nodeLabel,
text_node_property:
textNodeProperties.length > 0
? textNodeProperties
: [this.textNodeProperty],
}
);
if (indexInformation) {
// Sort the index information by index name
const sortedIndexInformation = this.sortByIndexName(
indexInformation,
this.indexName
);
try {
const [index] = sortedIndexInformation;
const [labelOrType] = index.labelsOrTypes;
const [property] = index.properties;
this.keywordIndexName = index.name;
this.textNodeProperty = property;
this.nodeLabel = labelOrType;
return labelOrType;
} catch (error) {
return null;
}
}
return null;
}
async createNewKeywordIndex(
textNodeProperties: string[] = []
): Promise<void> {
const nodeProps =
textNodeProperties.length > 0
? textNodeProperties
: [this.textNodeProperty];
// Construct the Cypher query to create a new full text index
const ftsIndexQuery = `
CREATE FULLTEXT INDEX ${this.keywordIndexName}
FOR (n:\`${this.nodeLabel}\`) ON EACH
[${nodeProps.map((prop) => `n.\`${prop}\``).join(", ")}]
`;
await this.query(ftsIndexQuery);
}
sortByIndexName(
values: Array<{ [key: string]: Any }>,
indexName: string
): Array<{ [key: string]: Any }> {
return values.sort(
(a, b) =>
(a.name === indexName ? -1 : 0) - (b.name === indexName ? -1 : 0)
);
}
async addVectors(
vectors: number[][],
documents: Document[],
metadatas?: Record<string, Any>[],
ids?: string[]
): Promise<string[]> {
let _ids = ids;
const _metadatas = metadatas;
if (!_ids) {
_ids = documents.map(() => uuid.v1());
}
const importQuery = `
UNWIND $data AS row
CALL {
WITH row
MERGE (c:\`${this.nodeLabel}\` {id: row.id})
WITH c, row
CALL db.create.setVectorProperty(c, '${this.embeddingNodeProperty}', row.embedding)
YIELD node
SET c.\`${this.textNodeProperty}\` = row.text
SET c += row.metadata
} IN TRANSACTIONS OF 1000 ROWS
`;
const parameters = {
data: documents.map(({ pageContent, metadata }, index) => ({
text: pageContent,
metadata: _metadatas ? _metadatas[index] : metadata,
embedding: vectors[index],
id: _ids ? _ids[index] : null,
})),
};
await this.query(importQuery, parameters);
return _ids;
}
async addDocuments(documents: Document[]): Promise<string[]> {
const texts = documents.map(({ pageContent }) => pageContent);
return this.addVectors(
await this.embeddings.embedDocuments(texts),
documents
);
}
async similaritySearch(
query: string,
k = 4,
params: Record<string, Any> = {}
): Promise<Document[]> {
const embedding = await this.embeddings.embedQuery(query);
const results = await this.similaritySearchVectorWithScore(
embedding,
k,
query,
params
);
return results.map((result) => result[0]);
}
async similaritySearchVectorWithScore(
vector: number[],
k: number,
query: string,
params: Record<string, Any> = {}
): Promise<[Document, number][]> {
let indexQuery: string;
let filterParams: Record<string, Any>;
const { filter } = params;
if (filter) {
if (!this.supportMetadataFilter) {
throw new Error(
"Metadata filtering is only supported in Neo4j version 5.18 or greater."
);
}
if (this.searchType === "hybrid") {
throw new Error(
"Metadata filtering can't be use in combination with a hybrid search approach."
);
}
const parallelQuery = this.isEnterprise
? "CYPHER runtime = parallel parallelRuntimeSupport=all "
: "";
const baseIndexQuery = `
${parallelQuery}
MATCH (n:\`${this.nodeLabel}\`)
WHERE n.\`${this.embeddingNodeProperty}\` IS NOT NULL
AND size(n.\`${this.embeddingNodeProperty}\`) = toInteger(${this.embeddingDimension}) AND
`;
const baseCosineQuery = `
WITH n as node, vector.similarity.cosine(
n.\`${this.embeddingNodeProperty}\`,
$embedding
) AS score ORDER BY score DESC LIMIT toInteger($k)
`;
const [fSnippets, fParams] = constructMetadataFilter(filter);
indexQuery = baseIndexQuery + fSnippets + baseCosineQuery;
filterParams = fParams;
} else {
indexQuery = getSearchIndexQuery(this.searchType, this.indexType);
filterParams = {};
}
let defaultRetrieval: string;
if (this.indexType === "RELATIONSHIP") {
defaultRetrieval = `
RETURN relationship.${this.textNodeProperty} AS text, score,
relationship {.*, ${this.textNodeProperty}: Null,
${this.embeddingNodeProperty}: Null, id: Null } AS metadata
`;
} else {
defaultRetrieval = `
RETURN node.${this.textNodeProperty} AS text, score,
node {.*, ${this.textNodeProperty}: Null,
${this.embeddingNodeProperty}: Null, id: Null } AS metadata
`;
}
const retrievalQuery = this.retrievalQuery
? this.retrievalQuery
: defaultRetrieval;
const readQuery = `${indexQuery} ${retrievalQuery}`;
const parameters = {
index: this.indexName,
k: Number(k),
embedding: vector,
keyword_index: this.keywordIndexName,
query: removeLuceneChars(query),
...params,
...filterParams,
};
const results = await this.query(readQuery, parameters);
if (results) {
if (results.some((result) => result.text == null)) {
if (!this.retrievalQuery) {
throw new Error(
"Make sure that none of the '" +
this.textNodeProperty +
"' properties on nodes with label '" +
this.nodeLabel +
"' are missing or empty"
);
} else {
throw new Error(
"Inspect the 'retrievalQuery' and ensure it doesn't return null for the 'text' column"
);
}
}
const docs: [Document, number][] = results.map((result: Any) => [
new Document({
pageContent: result.text,
metadata: Object.fromEntries(
Object.entries(result.metadata).filter(([_, v]) => v !== null)
),
}),
result.score,
]);
return docs;
}
return [];
}
}
function toObjects(records: neo4j.Record[]) {
const recordValues: Record<string, Any>[] = records.map((record) => {
const rObj = record.toObject();
const out: { [key: string]: Any } = {};
Object.keys(rObj).forEach((key) => {
out[key] = itemIntToString(rObj[key]);
});
return out;
});
return recordValues;
}
function itemIntToString(item: Any): Any {
if (neo4j.isInt(item)) return item.toString();
if (Array.isArray(item)) return item.map((ii) => itemIntToString(ii));
if (["number", "string", "boolean"].indexOf(typeof item) !== -1) return item;
if (item === null) return item;
if (typeof item === "object") return objIntToString(item);
}
function objIntToString(obj: Any) {
const entry = extractFromNeoObjects(obj);
let newObj: Any = null;
if (Array.isArray(entry)) {
newObj = entry.map((item) => itemIntToString(item));
} else if (entry !== null && typeof entry === "object") {
newObj = {};
Object.keys(entry).forEach((key) => {
newObj[key] = itemIntToString(entry[key]);
});
}
return newObj;
}
function extractFromNeoObjects(obj: Any) {
if (
// eslint-disable-next-line
obj instanceof (neo4j.types.Node as any) ||
// eslint-disable-next-line
obj instanceof (neo4j.types.Relationship as any)
) {
return obj.properties;
// eslint-disable-next-line
} else if (obj instanceof (neo4j.types.Path as any)) {
// eslint-disable-next-line
return [].concat.apply<any[], any[], any[]>([], extractPathForRows(obj));
}
return obj;
}
function extractPathForRows(path: neo4j.Path) {
let { segments } = path;
// Zero length path. No relationship, end === start
if (!Array.isArray(path.segments) || path.segments.length < 1) {
segments = [{ ...path, end: null } as Any];
}
return segments.map((segment: Any) =>
[
objIntToString(segment.start),
objIntToString(segment.relationship),
objIntToString(segment.end),
].filter((part) => part !== null)
);
}
function getSearchIndexQuery(
searchType: SearchType,
indexType: IndexType = DEFAULT_INDEX_TYPE
): string {
if (indexType === "NODE") {
const typeToQueryMap: { [key in SearchType]: string } = {
vector:
"CALL db.index.vector.queryNodes($index, $k, $embedding) YIELD node, score",
hybrid: `
CALL {
CALL db.index.vector.queryNodes($index, $k, $embedding) YIELD node, score
WITH collect({node:node, score:score}) AS nodes, max(score) AS max
UNWIND nodes AS n
// We use 0 as min
RETURN n.node AS node, (n.score / max) AS score UNION
CALL db.index.fulltext.queryNodes($keyword_index, $query, {limit: $k}) YIELD node, score
WITH collect({node: node, score: score}) AS nodes, max(score) AS max
UNWIND nodes AS n
RETURN n.node AS node, (n.score / max) AS score
}
WITH node, max(score) AS score ORDER BY score DESC LIMIT toInteger($k)
`,
};
return typeToQueryMap[searchType];
} else {
return `
CALL db.index.vector.queryRelationships($index, $k, $embedding)
YIELD relationship, score
`;
}
}
function removeLuceneChars(text: string | null) {
if (text === undefined || text === null) {
return null;
}
// Remove Lucene special characters
const specialChars = [
"+",
"-",
"&",
"|",
"!",
"(",
")",
"{",
"}",
"[",
"]",
"^",
'"',
"~",
"*",
"?",
":",
"\\",
];
let modifiedText = text;
for (const char of specialChars) {
modifiedText = modifiedText.split(char).join(" ");
}
return modifiedText.trim();
}
function isVersionLessThan(v1: number[], v2: number[]): boolean {
for (let i = 0; i < Math.min(v1.length, v2.length); i += 1) {
if (v1[i] < v2[i]) {
return true;
} else if (v1[i] > v2[i]) {
return false;
}
}
// If all the corresponding parts are equal, the shorter version is less
return v1.length < v2.length;
}
// Filter utils
const COMPARISONS_TO_NATIVE: Record<string, string> = {
$eq: "=",
$ne: "<>",
$lt: "<",
$lte: "<=",
$gt: ">",
$gte: ">=",
};
const COMPARISONS_TO_NATIVE_OPERATORS = new Set(
Object.keys(COMPARISONS_TO_NATIVE)
);
const TEXT_OPERATORS = new Set(["$like", "$ilike"]);
const LOGICAL_OPERATORS = new Set(["$and", "$or"]);
const SPECIAL_CASED_OPERATORS = new Set(["$in", "$nin", "$between"]);
const SUPPORTED_OPERATORS = new Set([
...COMPARISONS_TO_NATIVE_OPERATORS,
...TEXT_OPERATORS,
...LOGICAL_OPERATORS,
...SPECIAL_CASED_OPERATORS,
]);
const IS_IDENTIFIER_REGEX = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
function combineQueries(
inputQueries: [string, Record<string, Any>][],
operator: string
): [string, Record<string, Any>] {
let combinedQuery = "";
const combinedParams: Record<string, Any> = {};
const paramCounter: Record<string, number> = {};
for (const [query, params] of inputQueries) {
let newQuery = query;
for (const [param, value] of Object.entries(params)) {
if (param in paramCounter) {
paramCounter[param] += 1;
} else {
paramCounter[param] = 1;
}
const newParamName = `${param}_${paramCounter[param]}`;
newQuery = newQuery.replace(`$${param}`, `$${newParamName}`);
combinedParams[newParamName] = value;
}
if (combinedQuery) {
combinedQuery += ` ${operator} `;
}
combinedQuery += `(${newQuery})`;
}
return [combinedQuery, combinedParams];
}
function collectParams(
inputData: [string, Record<string, string>][]
): [string[], Record<string, Any>] {
const queryParts: string[] = [];
const params: Record<string, Any> = {};
for (const [queryPart, param] of inputData) {
queryParts.push(queryPart);
Object.assign(params, param);
}
return [queryParts, params];
}
function handleFieldFilter(
field: string,
value: Any,
paramNumber = 1
): [string, Record<string, Any>] {
if (typeof field !== "string") {
throw new Error(
`field should be a string but got: ${typeof field} with value: ${field}`
);
}
if (field.startsWith("$")) {
throw new Error(
`Invalid filter condition. Expected a field but got an operator: ${field}`
);
}
// Allow [a - zA - Z0 -9_], disallow $ for now until we support escape characters
if (!IS_IDENTIFIER_REGEX.test(field)) {
throw new Error(
`Invalid field name: ${field}. Expected a valid identifier.`
);
}
let operator: string;