diff --git a/examples/readonly.ts b/examples/readonly.ts new file mode 100644 index 0000000000000000000000000000000000000000..180cb8c0fefdd874d4d1228519d9fe52d7c44e0e --- /dev/null +++ b/examples/readonly.ts @@ -0,0 +1,37 @@ +import { execSync } from "child_process"; +import { + PDFReader, + serviceContextFromDefaults, + storageContextFromDefaults, + VectorStoreIndex, +} from "llamaindex"; + +const STORAGE_DIR = "./cache"; + +async function main() { + // write the index to disk + const serviceContext = serviceContextFromDefaults({}); + const storageContext = await storageContextFromDefaults({ + persistDir: `${STORAGE_DIR}`, + }); + const reader = new PDFReader(); + const documents = await reader.loadData("data/brk-2022.pdf"); + await VectorStoreIndex.fromDocuments(documents, { + storageContext, + serviceContext, + }); + console.log("wrote index to disk - now trying to read it"); + // make index dir read only + execSync(`chmod -R 555 ${STORAGE_DIR}`); + // reopen index + const readOnlyStorageContext = await storageContextFromDefaults({ + persistDir: `${STORAGE_DIR}`, + }); + await VectorStoreIndex.init({ + storageContext: readOnlyStorageContext, + serviceContext, + }); + console.log("read only index successfully opened"); +} + +main().catch(console.error); diff --git a/packages/core/src/indices/vectorStore/VectorStoreIndex.ts b/packages/core/src/indices/vectorStore/VectorStoreIndex.ts index d2452962dcbbb21e0e007e4823b648601e1d39cf..08499e5e981448f2fdd54559e29defe6fbba0d76 100644 --- a/packages/core/src/indices/vectorStore/VectorStoreIndex.ts +++ b/packages/core/src/indices/vectorStore/VectorStoreIndex.ts @@ -87,24 +87,23 @@ export class VectorStoreIndex extends BaseIndex<IndexDict> { ); } - if (!indexStruct && !options.nodes) { + if (options.nodes) { + // If nodes are passed in, then we need to update the index + indexStruct = await VectorStoreIndex.buildIndexFromNodes( + options.nodes, + serviceContext, + vectorStore, + docStore, + indexStruct, + ); + + await indexStore.addIndexStruct(indexStruct); + } else if (!indexStruct) { throw new Error( "Cannot initialize VectorStoreIndex without nodes or indexStruct", ); } - const nodes = options.nodes ?? []; - - indexStruct = await VectorStoreIndex.buildIndexFromNodes( - nodes, - serviceContext, - vectorStore, - docStore, - indexStruct, - ); - - await indexStore.addIndexStruct(indexStruct); - return new VectorStoreIndex({ storageContext, serviceContext,