File size: 2,167 Bytes
0a50834
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import re

from neo4j import GraphDatabase


def identifier(value):
    if not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', value):
        raise ValueError('Invalid Cypher identifier: ' + value)
    return '`' + value + '`'


class Graph:
    def __init__(self):
        self.driver = GraphDatabase.driver(os.getenv('NEO4J_URI', 'bolt://neo4j:7687'), auth=(os.getenv('NEO4J_USERNAME', 'neo4j'), os.environ['NEO4J_PASSWORD']), notifications_min_severity='OFF')
        self.database = os.getenv('NEO4J_DATABASE', 'neo4j')

    def run(self, query, **params):
        with self.driver.session(database=self.database) as session:
            return [dict(record) for record in session.run(query, **params)]

    def check_source(self, target, prop, source):
        p = identifier(prop)
        marker = identifier(prop + '__source')
        mismatch = self.run(f'MATCH (n:{target.label}) WHERE n.{p} IS NOT NULL AND (n.{marker} IS NULL OR n.{marker} <> $source) RETURN count(n) AS n', source=source)[0]['n']
        if mismatch:
            raise ValueError(f'{mismatch} existing vectors have different or unknown provenance. Use a different --property or a fresh graph.')

    def missing(self, target, ids, prop):
        rows = self.run(f'UNWIND $ids AS key OPTIONAL MATCH (n:{target.label} {{{target.key}:key}}) RETURN key,n IS NOT NULL AS found,n.{identifier(prop)} IS NULL AS missing', ids=ids)
        if len(rows) != len(ids) or not all(row['found'] for row in rows):
            raise ValueError('Parquet keys do not match this graph snapshot.')
        return {row['key'] for row in rows if row['missing']}

    def write(self, target, prop, source, rows):
        if not rows:
            return
        result = self.run(f'UNWIND $rows AS row MATCH (n:{target.label} {{{target.key}:row.key}}) WHERE n.{identifier(prop)} IS NULL SET n.{identifier(prop)}=row.vector,n.{identifier(prop + "__source")}=$source RETURN count(n) AS n', rows=rows, source=source)
        if result[0]['n'] != len(rows):
            raise RuntimeError('Graph changed during writing; stop concurrent vector writers and retry.')

    def close(self):
        self.driver.close()