|
| 1 | +/** |
| 2 | + * Neo4j Migration: Add point-lookup indexes on Envelope.id and MetaEnvelope.id |
| 3 | + * |
| 4 | + * Without these, every `MATCH (e:Envelope { id: $id })` and |
| 5 | + * `MATCH (m:MetaEnvelope { id: $id })` does a NodeByLabelScan over the entire |
| 6 | + * Envelope / MetaEnvelope population, which scales linearly with total stored |
| 7 | + * data. Update operations call these queries once per payload field, so a |
| 8 | + * 5-field chat update can take 10+ seconds. |
| 9 | + * |
| 10 | + * `id` is generated by W3IDBuilder and is unique by construction, so a plain |
| 11 | + * range index on the property is sufficient — no need for a composite index |
| 12 | + * with eName, since the id alone is selective. |
| 13 | + */ |
| 14 | + |
| 15 | +import type { Driver } from "neo4j-driver"; |
| 16 | + |
| 17 | +const STATEMENTS: { name: string; cypher: string }[] = [ |
| 18 | + { |
| 19 | + name: "envelope_id_index", |
| 20 | + cypher: `CREATE INDEX envelope_id_index IF NOT EXISTS FOR (e:Envelope) ON (e.id)`, |
| 21 | + }, |
| 22 | + { |
| 23 | + name: "meta_envelope_id_index", |
| 24 | + cypher: `CREATE INDEX meta_envelope_id_index IF NOT EXISTS FOR (m:MetaEnvelope) ON (m.id)`, |
| 25 | + }, |
| 26 | +]; |
| 27 | + |
| 28 | +export async function createIdIndexes(driver: Driver): Promise<void> { |
| 29 | + const session = driver.session(); |
| 30 | + try { |
| 31 | + for (const { name, cypher } of STATEMENTS) { |
| 32 | + try { |
| 33 | + await session.run(cypher); |
| 34 | + console.log(`Ensured ${name}`); |
| 35 | + } catch (error) { |
| 36 | + if ( |
| 37 | + error instanceof Error && |
| 38 | + error.message.includes("already exists") |
| 39 | + ) { |
| 40 | + console.log(`${name} already exists`); |
| 41 | + } else { |
| 42 | + console.error(`Error creating ${name}:`, error); |
| 43 | + throw error; |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + } finally { |
| 48 | + await session.close(); |
| 49 | + } |
| 50 | +} |
0 commit comments