File size: 1,986 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
from ._graph import identifier
from .config import TARGETS


def create_indexes(graph, targets, prop, timeout):
    for name in targets:
        target = TARGETS[name]
        field = prop or target.property
        index = f'{target.label}_{field}_vector' if prop else target.index
        dims = graph.run(f'MATCH (n:{target.label}) WHERE n.{identifier(field)} IS NOT NULL RETURN DISTINCT size(n.{identifier(field)}) AS dim')
        if len(dims) != 1 or not 1 <= dims[0]['dim'] <= 4096:
            raise ValueError(f'{name}: requires nonempty vectors with one dimension in 1..4096.')
        existing = graph.run('SHOW INDEXES YIELD name,type,labelsOrTypes,properties,options WHERE name=$name RETURN type,labelsOrTypes,properties,options', name=index)
        if existing:
            row = existing[0]
            if (row['type'], row['labelsOrTypes'], row['properties']) != ('VECTOR', [target.label], [field]) or row['options']['indexConfig'].get('vector.dimensions') != dims[0]['dim']:
                raise ValueError('Existing index conflicts with requested vectors: ' + index)
        else:
            graph.run(f'CREATE VECTOR INDEX {identifier(index)} FOR (n:{target.label}) ON (n.{identifier(field)}) OPTIONS {{indexConfig: {{`vector.dimensions`: $dim, `vector.similarity_function`: "cosine"}}}}', dim=dims[0]['dim'])
        graph.run('CALL db.awaitIndex($name,$timeout)', name=index, timeout=timeout)
        print('Index ready:', index, flush=True)


def inspect_graph(graph):
    return {
        'nodes': graph.run('MATCH (n) UNWIND labels(n) AS label RETURN label,count(*) AS count ORDER BY label'),
        'relationships': graph.run('MATCH ()-[r]->() RETURN type(r) AS type,count(*) AS count ORDER BY type'),
        'vectors': {name: graph.run(f'MATCH (n:{target.label}) RETURN count(n.{target.property}) AS count')[0]['count'] for name, target in TARGETS.items()},
        'indexes': graph.run('SHOW INDEXES YIELD name,type,state RETURN name,type,state'),
    }