20250522105040-delete-old-index-for-vector-store-file-relation.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import mongoose from 'mongoose';
  2. import { getMongoUri, mongoOptions } from '~/server/util/mongoose-utils';
  3. import loggerFactory from '~/utils/logger';
  4. const logger = loggerFactory(
  5. 'growi:migrate:vector-store-file-relation-index-migration',
  6. );
  7. async function dropIndexIfExists(db, collectionName, indexName) {
  8. // check existence of the collection
  9. const items = await db
  10. .listCollections({ name: collectionName }, { nameOnly: true })
  11. .toArray();
  12. if (items.length === 0) {
  13. return;
  14. }
  15. const collection = await db.collection(collectionName);
  16. if (await collection.indexExists(indexName)) {
  17. await collection.dropIndex(indexName);
  18. }
  19. }
  20. module.exports = {
  21. async up(db) {
  22. logger.info('Apply migration');
  23. await mongoose.connect(getMongoUri(), mongoOptions);
  24. // Drop old index
  25. await dropIndexIfExists(
  26. db,
  27. 'vectorstorefilerelations',
  28. 'vectorStoreRelationId_1_page_1',
  29. );
  30. // Create index
  31. const collection = mongoose.connection.collection(
  32. 'vectorstorefilerelations',
  33. );
  34. await collection.createIndex(
  35. { vectorStoreRelationId: 1, page: 1, attachment: 1 },
  36. { unique: true },
  37. );
  38. },
  39. async down(db) {
  40. logger.info('Rollback migration');
  41. await mongoose.connect(getMongoUri(), mongoOptions);
  42. // Drop new index
  43. await dropIndexIfExists(
  44. db,
  45. 'vectorstorefilerelations',
  46. 'vectorStoreRelationId_1_page_1_attachment_1',
  47. );
  48. // Recreate old index
  49. const collection = mongoose.connection.collection(
  50. 'vectorstorefilerelations',
  51. );
  52. await collection.createIndex(
  53. { vectorStoreRelationId: 1, page: 1 },
  54. { unique: true },
  55. );
  56. },
  57. };