{"version":3,"file":"azure_cosmosdb_nosql.cjs","names":["VectorStore","CosmosClient","DefaultAzureCredential","Document"],"sources":["../src/azure_cosmosdb_nosql.ts"],"sourcesContent":["import type { EmbeddingsInterface } from \"@langchain/core/embeddings\";\nimport {\n  MaxMarginalRelevanceSearchOptions,\n  VectorStore,\n} from \"@langchain/core/vectorstores\";\nimport { Document, DocumentInterface } from \"@langchain/core/documents\";\nimport { maximalMarginalRelevance } from \"@langchain/core/utils/math\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport {\n  Container,\n  ContainerRequest,\n  CosmosClient,\n  CosmosClientOptions,\n  DatabaseRequest,\n  FullTextPolicy,\n  IndexingPolicy,\n  SqlParameter,\n  SqlQuerySpec,\n  VectorEmbedding,\n  VectorEmbeddingPolicy,\n  VectorIndex,\n} from \"@azure/cosmos\";\nimport { DefaultAzureCredential, TokenCredential } from \"@azure/identity\";\n\n/** Azure Cosmos DB for NoSQL search types. */\nexport const AzureCosmosDBNoSQLSearchType = {\n  /** Vector similarity search. */\n  Vector: \"vector\",\n  /** Vector search with score threshold filtering. */\n  VectorScoreThreshold: \"vector_score_threshold\",\n  /** Full-text search only (preview feature). */\n  FullTextSearch: \"full_text_search\",\n  /** Full-text search with BM25 ranking (preview feature). */\n  FullTextRanking: \"full_text_ranking\",\n  /** Hybrid search combining vector and full-text search with RRF (preview feature). */\n  Hybrid: \"hybrid\",\n  /** Hybrid search with score threshold filtering (preview feature). */\n  HybridScoreThreshold: \"hybrid_score_threshold\",\n} as const;\n\n/** Azure Cosmos DB for NoSQL search type. */\nexport type AzureCosmosDBNoSQLSearchType =\n  (typeof AzureCosmosDBNoSQLSearchType)[keyof typeof AzureCosmosDBNoSQLSearchType];\n\n/** Re-export FullTextPolicy and VectorIndex types from @azure/cosmos for convenience. */\nexport type { FullTextPolicy, VectorIndex } from \"@azure/cosmos\";\n\n/**\n * Full-text rank filter item for full-text ranking queries.\n * Each item specifies a field to search and the search text.\n */\nexport interface AzureCosmosDBNoSQLFullTextRankFilter {\n  /** The field to search. */\n  searchField: string;\n  /** The search text. */\n  searchText: string;\n}\n\n/**\n * Projection mapping for custom field selection.\n * Maps field names to their aliases in the query results.\n */\nexport type ProjectionMapping = Record<string, string>;\n\n/** Azure Cosmos DB for NoSQL query filter. */\nexport type AzureCosmosDBNoSQLQueryFilter = string | SqlQuerySpec;\n\n/** Azure Cosmos DB for NoSQL filter type. */\nexport type AzureCosmosDBNoSQLFilterType = {\n  /**\n   * SQL filter clause to add to the search query.\n   * @example 'WHERE c.category = \"cars\"'\n   */\n  filterClause?: AzureCosmosDBNoSQLQueryFilter;\n  /** Determines whether or not to include the embeddings in the search results. */\n  includeEmbeddings?: boolean;\n  /** Search type override for this query. Takes precedence over the default search type. */\n  searchType?: AzureCosmosDBNoSQLSearchType;\n  /**\n   * Full-text rank filter for full-text ranking queries.\n   * Each item specifies a field to search and the search text.\n   */\n  fullTextRankFilter?: AzureCosmosDBNoSQLFullTextRankFilter[];\n  /**\n   * Projection mapping for custom field selection.\n   * Maps field names to their paths in the document.\n   */\n  projectionMapping?: ProjectionMapping;\n  /**\n   * Offset and limit clause for pagination.\n   * @example 'OFFSET 10 LIMIT 20'\n   */\n  offsetLimit?: string;\n  /**\n   * Weights for hybrid search RRF (Reciprocal Rank Fusion).\n   * Typically two values: [vectorWeight, fullTextWeight].\n   */\n  weights?: number[];\n  /**\n   * Score threshold for filtering results.\n   * Only results with a score >= threshold are returned.\n   */\n  threshold?: number;\n};\n\n/** Azure Cosmos DB for NoSQL Delete Parameters. */\nexport type AzureCosmosDBNoSqlDeleteParams = {\n  /** List of IDs for the documents to be removed. */\n  readonly ids?: string | string[];\n  /** SQL query to select the documents to be removed. */\n  readonly filter?: AzureCosmosDBNoSQLQueryFilter;\n};\n\n/** Azure Cosmos DB for NoSQL database creation options. */\nexport type AzureCosmosDBNoSqlCreateDatabaseOptions = Partial<\n  Omit<DatabaseRequest, \"id\">\n>;\n/** Azure Cosmos DB for NoSQL container creation options. */\nexport type AzureCosmosDBNoSqlCreateContainerOptions = Partial<\n  Omit<ContainerRequest, \"id\" | \"vectorEmbeddingPolicy\" | \"indexingPolicy\">\n>;\n\n/**\n * Initialization options for the Azure CosmosDB for NoSQL database and container.\n *\n * Note that if you provide multiple vector embeddings in the vectorEmbeddingPolicy,\n * the first one will be used for creating documents and searching.\n */\nexport interface AzureCosmosDBNoSQLInitOptions {\n  readonly vectorEmbeddingPolicy?: VectorEmbeddingPolicy;\n  readonly indexingPolicy?: IndexingPolicy;\n  /**\n   * Full-text policy for the container (preview feature).\n   * Required when fullTextSearchEnabled is true.\n   */\n  readonly fullTextPolicy?: FullTextPolicy;\n  readonly createContainerOptions?: AzureCosmosDBNoSqlCreateContainerOptions;\n  readonly createDatabaseOptions?: AzureCosmosDBNoSqlCreateDatabaseOptions;\n}\n\n/**\n * Configuration options for the `AzureCosmosDBNoSQLVectorStore` constructor.\n */\nexport interface AzureCosmosDBNoSQLConfig extends AzureCosmosDBNoSQLInitOptions {\n  /** Pre-configured CosmosClient instance. If provided, connectionString and endpoint are ignored. */\n  readonly client?: CosmosClient;\n  /** Cosmos DB connection string. */\n  readonly connectionString?: string;\n  /** Cosmos DB endpoint URL (used with credentials for Azure AD authentication). */\n  readonly endpoint?: string;\n  /** Azure credential for authentication (defaults to DefaultAzureCredential). */\n  readonly credentials?: TokenCredential;\n  /** Database name. Defaults to \"vectorSearchDB\". */\n  readonly databaseName?: string;\n  /** Container name. Defaults to \"vectorSearchContainer\". */\n  readonly containerName?: string;\n  /** Document field name for the text content. Defaults to \"text\". */\n  readonly textKey?: string;\n  /** Document field name for the metadata. Defaults to \"metadata\". */\n  readonly metadataKey?: string;\n  /**\n   * Enable full-text search capabilities (preview feature).\n   * When enabled, fullTextPolicy and appropriate indexingPolicy must be configured.\n   */\n  readonly fullTextSearchEnabled?: boolean;\n  /** Table alias used in Cosmos DB SQL queries. Defaults to \"c\". */\n  readonly tableAlias?: string;\n  /**\n   * Default search type to use when no search type is specified in the filter.\n   * Defaults to \"vector\".\n   */\n  readonly defaultSearchType?: AzureCosmosDBNoSQLSearchType;\n}\n\nconst USER_AGENT_SUFFIX = \"langchainjs-cdbnosql-vectorstore-javascript\";\n\n/**\n * Azure Cosmos DB for NoSQL vector store.\n * To use this, you should have both:\n * - the `@azure/cosmos` NPM package installed\n * - a connection string associated with a NoSQL instance\n *\n * You do not need to create a database or container, it will be created\n * automatically.\n *\n * @example\n * ```typescript\n * const vectorStore = new AzureCosmosDBNoSQLVectorStore(\n *   new OpenAIEmbeddings(),\n *   {\n *     databaseName: \"mydb\",\n *     containerName: \"vectors\",\n *   }\n * );\n * await vectorStore.addDocuments(docs);\n * const results = await vectorStore.similaritySearch(\"query\", 4);\n * ```\n */\nexport class AzureCosmosDBNoSQLVectorStore extends VectorStore {\n  declare FilterType: AzureCosmosDBNoSQLFilterType;\n\n  get lc_secrets(): { [key: string]: string } {\n    return {\n      connectionString: \"AZURE_COSMOSDB_NOSQL_CONNECTION_STRING\",\n    };\n  }\n\n  private initPromise?: Promise<void>;\n\n  private readonly client: CosmosClient;\n\n  private container: Container;\n\n  private readonly textKey: string;\n\n  private readonly metadataKey: string;\n\n  private embeddingKey: string;\n\n  private readonly fullTextSearchEnabled: boolean;\n\n  private readonly tableAlias: string;\n\n  private readonly fullTextPolicy?: FullTextPolicy;\n\n  private readonly defaultSearchType: AzureCosmosDBNoSQLSearchType;\n\n  /**\n   * Initializes the AzureCosmosDBNoSQLVectorStore.\n   * Connects the client to the database and creates the container if needed.\n   * @returns A promise that resolves when the AzureCosmosDBNoSQLVectorStore has been initialized.\n   */\n  initialize: () => Promise<void>;\n\n  _vectorstoreType(): string {\n    return \"azure_cosmosdb_nosql\";\n  }\n\n  constructor(\n    embeddings: EmbeddingsInterface,\n    dbConfig: AzureCosmosDBNoSQLConfig\n  ) {\n    super(embeddings, dbConfig);\n\n    const connectionString =\n      dbConfig.connectionString ??\n      getEnvironmentVariable(\"AZURE_COSMOSDB_NOSQL_CONNECTION_STRING\");\n\n    const endpoint =\n      dbConfig.endpoint ??\n      getEnvironmentVariable(\"AZURE_COSMOSDB_NOSQL_ENDPOINT\");\n\n    if (!dbConfig.client && !connectionString && !endpoint) {\n      throw new Error(\n        \"AzureCosmosDBNoSQLVectorStore client, connection string or endpoint must be set.\"\n      );\n    }\n\n    if (!dbConfig.client) {\n      if (connectionString) {\n        this.client = new CosmosClient({\n          connectionString,\n          userAgentSuffix: USER_AGENT_SUFFIX,\n        });\n      } else {\n        // Use managed identity\n        this.client = new CosmosClient({\n          endpoint,\n          aadCredentials: dbConfig.credentials ?? new DefaultAzureCredential(),\n          userAgentSuffix: USER_AGENT_SUFFIX,\n        } as CosmosClientOptions);\n      }\n    }\n\n    const client = dbConfig.client || this.client;\n    const databaseName = dbConfig.databaseName ?? \"vectorSearchDB\";\n    const containerName = dbConfig.containerName ?? \"vectorSearchContainer\";\n    this.textKey = dbConfig.textKey ?? \"text\";\n    this.metadataKey = dbConfig.metadataKey ?? \"metadata\";\n    this.fullTextSearchEnabled = dbConfig.fullTextSearchEnabled ?? false;\n    this.tableAlias = dbConfig.tableAlias ?? \"c\";\n    this.fullTextPolicy = dbConfig.fullTextPolicy;\n    this.defaultSearchType =\n      dbConfig.defaultSearchType ?? AzureCosmosDBNoSQLSearchType.Vector;\n\n    const vectorEmbeddingPolicy = dbConfig.vectorEmbeddingPolicy ?? {\n      vectorEmbeddings: [],\n    };\n    const indexingPolicy = dbConfig.indexingPolicy ?? {\n      indexingMode: \"consistent\",\n      automatic: true,\n      includedPaths: [{ path: \"/*\" }],\n      excludedPaths: [{ path: \"/_etag/?\" }],\n    };\n\n    if (vectorEmbeddingPolicy.vectorEmbeddings.length === 0) {\n      vectorEmbeddingPolicy.vectorEmbeddings = [\n        {\n          path: \"/vector\",\n          dataType: \"float32\",\n          distanceFunction: \"cosine\",\n          // Will be determined automatically during initialization\n          dimensions: 0,\n        } as VectorEmbedding,\n      ];\n    }\n\n    if (!indexingPolicy.vectorIndexes?.length) {\n      indexingPolicy.vectorIndexes = [\n        {\n          path: \"/vector\",\n          type: \"quantizedFlat\",\n        } as VectorIndex,\n      ];\n    }\n\n    this.embeddingKey = vectorEmbeddingPolicy.vectorEmbeddings[0].path.slice(1);\n    if (!this.embeddingKey) {\n      throw new Error(\n        \"AzureCosmosDBNoSQLVectorStore requires a valid vectorEmbeddings path\"\n      );\n    }\n\n    // Validate full-text search configuration\n    if (this.fullTextSearchEnabled) {\n      if (\n        !indexingPolicy.fullTextIndexes ||\n        indexingPolicy.fullTextIndexes.length === 0\n      ) {\n        throw new Error(\n          \"fullTextIndexes cannot be null or empty in the indexingPolicy if full text search is enabled.\"\n        );\n      }\n      if (\n        !this.fullTextPolicy ||\n        !this.fullTextPolicy.fullTextPaths ||\n        this.fullTextPolicy.fullTextPaths.length === 0\n      ) {\n        throw new Error(\n          \"fullTextPolicy with fullTextPaths cannot be null or empty if full text search is enabled.\"\n        );\n      }\n    }\n\n    // Deferring initialization to the first call to `initialize`\n    this.initialize = () => {\n      if (this.initPromise === undefined) {\n        this.initPromise = this.init(client, databaseName, containerName, {\n          vectorEmbeddingPolicy,\n          indexingPolicy,\n          fullTextPolicy: this.fullTextPolicy,\n          createContainerOptions: dbConfig.createContainerOptions,\n          createDatabaseOptions: dbConfig.createDatabaseOptions,\n        }).catch((error) => {\n          console.error(\n            \"Error during AzureCosmosDBNoSQLVectorStore initialization:\",\n            error\n          );\n        });\n      }\n\n      return this.initPromise;\n    };\n  }\n\n  /**\n   * Removes specified documents from the AzureCosmosDBNoSQLVectorStore.\n   * If no IDs or filter are specified, all documents will be removed.\n   * @param params Parameters for the delete operation.\n   * @returns A promise that resolves when the documents have been removed.\n   */\n  async delete(params: AzureCosmosDBNoSqlDeleteParams = {}): Promise<void> {\n    await this.initialize();\n\n    if (params.ids && params.filter) {\n      throw new Error(\n        `AzureCosmosDBNoSQLVectorStore delete requires either \"ids\" or \"filter\" to be set in the params object, not both`\n      );\n    }\n\n    let ids: string[];\n    let query: AzureCosmosDBNoSQLQueryFilter | undefined = params.filter;\n\n    // Delete all documents\n    if (!params.ids && !params.filter) {\n      query = \"SELECT c.id FROM c\";\n    }\n\n    if (query) {\n      const { resources } = await this.container.items.query(query).fetchAll();\n      ids = resources.map((item) => item.id);\n    } else {\n      ids = (Array.isArray(params.ids) ? params.ids : [params.ids]) as string[];\n    }\n\n    if (ids.length === 0) {\n      return;\n    }\n\n    await Promise.all(ids.map((id) => this.container.item(id, id).delete()));\n  }\n\n  /**\n   * Gets the underlying Cosmos DB container.\n   * Useful for performing direct operations on the container.\n   * @returns The Cosmos DB container instance.\n   */\n  getContainer(): Container {\n    return this.container;\n  }\n\n  /**\n   * Method for adding vectors to the AzureCosmosDBNoSQLVectorStore.\n   * @param vectors Vectors to be added.\n   * @param documents Corresponding documents to be added.\n   * @returns A promise that resolves to the added documents IDs.\n   */\n  async addVectors(\n    vectors: number[][],\n    documents: DocumentInterface[]\n  ): Promise<string[]> {\n    await this.initialize();\n    const docs = vectors.map((embedding, idx) => ({\n      [this.textKey]: documents[idx].pageContent,\n      [this.embeddingKey]: embedding,\n      [this.metadataKey]: documents[idx].metadata,\n      ...(documents[idx].id ? { id: documents[idx].id } : {}),\n    }));\n\n    const ids: string[] = [];\n    const results = await Promise.all(\n      docs.map((doc) => this.container.items.create(doc))\n    );\n\n    for (const result of results) {\n      ids.push(result.resource?.id ?? \"error: could not create item\");\n    }\n\n    return ids;\n  }\n\n  /**\n   * Method for adding documents to the AzureCosmosDBNoSQLVectorStore. It first converts\n   * the documents to texts and then adds them as vectors.\n   * @param documents The documents to add.\n   * @returns A promise that resolves to the added documents IDs.\n   */\n  async addDocuments(documents: DocumentInterface[]): Promise<string[]> {\n    const texts = documents.map(({ pageContent }) => pageContent);\n    return this.addVectors(\n      await this.embeddings.embedDocuments(texts),\n      documents\n    );\n  }\n\n  /**\n   * Performs a similarity search on the vectors stored in the container.\n   * Routes to the appropriate search implementation based on the search type\n   * specified in the filter or the default search type configured for the vector store.\n   * @param queryVector Query vector for the similarity search.\n   * @param k Number of nearest neighbors to return. Defaults to 4.\n   * @param filter Optional filter options for the documents.\n   * @returns Promise that resolves to a list of documents and their corresponding similarity scores.\n   */\n  async similaritySearchVectorWithScore(\n    queryVector: number[],\n    k = 4,\n    filter: this[\"FilterType\"] | undefined = undefined\n  ): Promise<[Document, number][]> {\n    const searchType = filter?.searchType ?? this.defaultSearchType;\n\n    if (searchType === AzureCosmosDBNoSQLSearchType.Vector) {\n      return this.vectorSearchWithScore(queryVector, k, filter);\n    } else if (\n      searchType === AzureCosmosDBNoSQLSearchType.VectorScoreThreshold\n    ) {\n      return this.vectorSearchWithScoreThreshold(\n        queryVector,\n        k,\n        filter,\n        filter?.threshold\n      );\n    } else if (searchType === AzureCosmosDBNoSQLSearchType.Hybrid) {\n      if (\n        !filter?.fullTextRankFilter ||\n        filter.fullTextRankFilter.length === 0\n      ) {\n        throw new Error(\n          `fullTextRankFilter is required for ${searchType} search type`\n        );\n      }\n      return this.hybridSearchWithScore(\n        queryVector,\n        k,\n        filter,\n        filter.fullTextRankFilter\n      );\n    } else if (\n      searchType === AzureCosmosDBNoSQLSearchType.HybridScoreThreshold\n    ) {\n      if (\n        !filter?.fullTextRankFilter ||\n        filter.fullTextRankFilter.length === 0\n      ) {\n        throw new Error(\n          `fullTextRankFilter is required for ${searchType} search type`\n        );\n      }\n      return this.hybridSearchWithScoreThreshold(\n        queryVector,\n        k,\n        filter,\n        filter.fullTextRankFilter,\n        filter?.threshold\n      );\n    } else if (searchType === AzureCosmosDBNoSQLSearchType.FullTextSearch) {\n      return this.fullTextSearch(k, filter);\n    } else if (searchType === AzureCosmosDBNoSQLSearchType.FullTextRanking) {\n      if (!filter?.fullTextRankFilter) {\n        throw new Error(\n          `fullTextRankFilter is required for ${searchType} search type`\n        );\n      }\n      return this.fullTextRanking(k, filter, filter.fullTextRankFilter);\n    }\n    throw new Error(`Unrecognized search type '${searchType}'`);\n  }\n\n  /**\n   * Return documents selected using the maximal marginal relevance.\n   * Maximal marginal relevance optimizes for similarity to the query AND\n   * diversity among selected documents.\n   * @param query Text to look up documents similar to.\n   * @param options.k Number of documents to return.\n   * @param options.fetchK Number of documents to fetch before passing to\n   *     the MMR algorithm. Defaults to 20.\n   * @param options.lambda Number between 0 and 1 that determines the\n   *     degree of diversity among the results, where 0 corresponds to maximum\n   *     diversity and 1 to minimum diversity. Defaults to 0.5.\n   * @returns List of documents selected by maximal marginal relevance.\n   */\n  async maxMarginalRelevanceSearch(\n    query: string,\n    options: MaxMarginalRelevanceSearchOptions<this[\"FilterType\"]>\n  ): Promise<Document[]> {\n    const queryEmbedding = await this.embeddings.embedQuery(query);\n    return this.maxMarginalRelevanceSearchByVector(queryEmbedding, options);\n  }\n\n  /**\n   * Return documents selected using the maximal marginal relevance from a vector.\n   * Maximal marginal relevance optimizes for similarity to the query AND\n   * diversity among selected documents.\n   * @param queryEmbedding Query embedding vector.\n   * @param options.k Number of documents to return.\n   * @param options.fetchK Number of documents to fetch before passing to\n   *     the MMR algorithm. Defaults to 20.\n   * @param options.lambda Number between 0 and 1 that determines the\n   *     degree of diversity among the results, where 0 corresponds to maximum\n   *     diversity and 1 to minimum diversity. Defaults to 0.5.\n   * @returns List of documents selected by maximal marginal relevance.\n   */\n  async maxMarginalRelevanceSearchByVector(\n    queryEmbedding: number[],\n    options: MaxMarginalRelevanceSearchOptions<this[\"FilterType\"]>\n  ): Promise<Document[]> {\n    const { k, fetchK = 20, lambda = 0.5, filter } = options;\n    const includeEmbeddingsFlag = filter?.includeEmbeddings || false;\n\n    const docs = await this.similaritySearchVectorWithScore(\n      queryEmbedding,\n      fetchK,\n      {\n        ...filter,\n        includeEmbeddings: true,\n      }\n    );\n    const embeddingList = docs.map((doc) => doc[0].metadata[this.embeddingKey]);\n\n    // Re-rank the results using MMR\n    const mmrIndexes = maximalMarginalRelevance(\n      queryEmbedding,\n      embeddingList,\n      lambda,\n      k\n    );\n\n    return mmrIndexes.map((index) => {\n      const doc = docs[index][0];\n\n      // Remove embeddings if they were not requested originally\n      if (!includeEmbeddingsFlag) {\n        delete doc.metadata[this.embeddingKey];\n      }\n      return doc;\n    });\n  }\n\n  /**\n   * Initializes the AzureCosmosDBNoSQLVectorStore by connecting to the database.\n   * @param client The CosmosClient to use for connecting to the database.\n   * @param databaseName The name of the database to use.\n   * @param containerName The name of the container to use.\n   * @param initOptions Initialization options for the database and container.\n   * @returns A promise that resolves when the AzureCosmosDBNoSQLVectorStore has been initialized.\n   */\n  private async init(\n    client: CosmosClient,\n    databaseName: string,\n    containerName: string,\n    initOptions: AzureCosmosDBNoSQLInitOptions\n  ): Promise<void> {\n    // Determine vector dimensions if not provided\n    const vectorEmbeddingPolicy = initOptions.vectorEmbeddingPolicy!;\n    const needDimensions = vectorEmbeddingPolicy.vectorEmbeddings.some(\n      (v) => !v.dimensions\n    );\n    if (needDimensions) {\n      const queryEmbedding = await this.embeddings.embedQuery(\"test\");\n      for (const v of vectorEmbeddingPolicy.vectorEmbeddings) {\n        if (!v.dimensions) {\n          v.dimensions = queryEmbedding.length;\n        }\n      }\n    }\n\n    const { database } = await client.databases.createIfNotExists({\n      ...(initOptions?.createDatabaseOptions ?? {}),\n      id: databaseName,\n    });\n\n    const containerOptions = initOptions?.createContainerOptions ?? {};\n    const { container } = await database.containers.createIfNotExists({\n      ...containerOptions,\n      // Default partition key to /id if not specified\n      partitionKey: containerOptions.partitionKey ?? \"/id\",\n      indexingPolicy: initOptions?.indexingPolicy,\n      vectorEmbeddingPolicy,\n      fullTextPolicy: initOptions?.fullTextPolicy,\n      id: containerName,\n    });\n    this.container = container;\n  }\n\n  /**\n   * Performs a plain vector similarity search.\n   */\n  private async vectorSearchWithScore(\n    queryVector: number[],\n    k = 4,\n    filter: this[\"FilterType\"] | undefined = undefined\n  ): Promise<[Document, number][]> {\n    await this.initialize();\n\n    const { query, parameters } = this.constructQuery(\n      k,\n      AzureCosmosDBNoSQLSearchType.Vector,\n      {\n        embeddings: queryVector,\n        filterClause: filter?.filterClause,\n        offsetLimit: filter?.offsetLimit,\n        projectionMapping: filter?.projectionMapping,\n        withEmbedding: filter?.includeEmbeddings,\n      }\n    );\n\n    return this.executeQuery(\n      query,\n      AzureCosmosDBNoSQLSearchType.Vector,\n      parameters,\n      {\n        withEmbedding: filter?.includeEmbeddings,\n        projectionMapping: filter?.projectionMapping,\n      }\n    );\n  }\n\n  /**\n   * Performs hybrid search combining vector similarity and full-text search using RRF.\n   */\n  private async hybridSearchWithScore(\n    embeddings: number[],\n    k = 4,\n    filter: this[\"FilterType\"] | undefined = undefined,\n    fullTextRankFilter: AzureCosmosDBNoSQLFullTextRankFilter[]\n  ): Promise<[Document, number][]> {\n    const { query, parameters } = this.constructQuery(\n      k,\n      AzureCosmosDBNoSQLSearchType.Hybrid,\n      {\n        embeddings,\n        fullTextRankFilter,\n        offsetLimit: filter?.offsetLimit,\n        projectionMapping: filter?.projectionMapping,\n        withEmbedding: filter?.includeEmbeddings,\n        filterClause: filter?.filterClause,\n        weights: filter?.weights,\n      }\n    );\n\n    return this.executeQuery(\n      query,\n      AzureCosmosDBNoSQLSearchType.Hybrid,\n      parameters,\n      {\n        withEmbedding: filter?.includeEmbeddings,\n        projectionMapping: filter?.projectionMapping,\n      }\n    );\n  }\n\n  /**\n   * Performs hybrid search with score threshold filtering.\n   */\n  private async hybridSearchWithScoreThreshold(\n    embeddings: number[],\n    k = 4,\n    filter: this[\"FilterType\"] | undefined = undefined,\n    fullTextRankFilter: AzureCosmosDBNoSQLFullTextRankFilter[],\n    threshold: number = 0.5\n  ): Promise<[Document, number][]> {\n    const { query, parameters } = this.constructQuery(\n      k,\n      AzureCosmosDBNoSQLSearchType.HybridScoreThreshold,\n      {\n        embeddings,\n        fullTextRankFilter,\n        offsetLimit: filter?.offsetLimit,\n        projectionMapping: filter?.projectionMapping,\n        withEmbedding: filter?.includeEmbeddings,\n        filterClause: filter?.filterClause,\n        weights: filter?.weights,\n      }\n    );\n\n    return this.executeQuery(\n      query,\n      AzureCosmosDBNoSQLSearchType.HybridScoreThreshold,\n      parameters,\n      {\n        withEmbedding: filter?.includeEmbeddings,\n        projectionMapping: filter?.projectionMapping,\n        threshold,\n      }\n    );\n  }\n\n  /**\n   * Performs vector similarity search with score threshold filtering.\n   */\n  private async vectorSearchWithScoreThreshold(\n    embeddings: number[],\n    k = 4,\n    filter: this[\"FilterType\"] | undefined = undefined,\n    threshold: number = 0.5\n  ): Promise<[Document, number][]> {\n    const { query, parameters } = this.constructQuery(\n      k,\n      AzureCosmosDBNoSQLSearchType.VectorScoreThreshold,\n      {\n        embeddings,\n        filterClause: filter?.filterClause,\n        offsetLimit: filter?.offsetLimit,\n        projectionMapping: filter?.projectionMapping,\n        withEmbedding: filter?.includeEmbeddings,\n      }\n    );\n\n    return this.executeQuery(\n      query,\n      AzureCosmosDBNoSQLSearchType.VectorScoreThreshold,\n      parameters,\n      {\n        withEmbedding: filter?.includeEmbeddings,\n        projectionMapping: filter?.projectionMapping,\n        threshold,\n      }\n    );\n  }\n\n  /**\n   * Performs full-text search with BM25 ranking using RRF.\n   * Note: Full-text ranking is a preview feature.\n   */\n  private async fullTextRanking(\n    k = 4,\n    filter: this[\"FilterType\"] | undefined = undefined,\n    fullTextRankFilter: AzureCosmosDBNoSQLFullTextRankFilter[]\n  ): Promise<[Document, number][]> {\n    const { query, parameters } = this.constructQuery(\n      k,\n      AzureCosmosDBNoSQLSearchType.FullTextRanking,\n      {\n        offsetLimit: filter?.offsetLimit,\n        projectionMapping: filter?.projectionMapping,\n        fullTextRankFilter,\n        filterClause: filter?.filterClause,\n      }\n    );\n\n    return this.executeQuery(\n      query,\n      AzureCosmosDBNoSQLSearchType.FullTextRanking,\n      parameters,\n      {\n        withEmbedding: false,\n        projectionMapping: filter?.projectionMapping,\n      }\n    );\n  }\n\n  /**\n   * Performs basic full-text search without vector similarity.\n   * Note: Full-text search is a preview feature.\n   */\n  private async fullTextSearch(\n    k = 4,\n    filter: this[\"FilterType\"] | undefined = undefined\n  ): Promise<[Document, number][]> {\n    const { query, parameters } = this.constructQuery(\n      k,\n      AzureCosmosDBNoSQLSearchType.FullTextSearch,\n      {\n        offsetLimit: filter?.offsetLimit,\n        projectionMapping: filter?.projectionMapping,\n        filterClause: filter?.filterClause,\n      }\n    );\n\n    return this.executeQuery(\n      query,\n      AzureCosmosDBNoSQLSearchType.FullTextSearch,\n      parameters,\n      {\n        withEmbedding: false,\n        projectionMapping: filter?.projectionMapping,\n      }\n    );\n  }\n\n  /**\n   * Constructs a Cosmos DB SQL query string and parameters based on the search type and options.\n   * Builds the complete SQL query including SELECT clause, projections, FROM clause,\n   * WHERE conditions, ORDER BY clauses (with RRF for hybrid/full-text), and pagination.\n   *\n   * @param k The maximum number of results to return.\n   * @param searchType The type of search to perform.\n   * @param options Configuration options including embeddings, filters, projections, and search-specific parameters.\n   * @returns An object containing the constructed SQL query string and an array of parameters.\n   */\n  private constructQuery(\n    k: number,\n    searchType: AzureCosmosDBNoSQLSearchType,\n    options: {\n      embeddings?: number[];\n      fullTextRankFilter?: AzureCosmosDBNoSQLFullTextRankFilter[];\n      offsetLimit?: string;\n      projectionMapping?: ProjectionMapping;\n      withEmbedding?: boolean;\n      filterClause?: AzureCosmosDBNoSQLQueryFilter;\n      weights?: number[];\n    }\n  ): { query: string; parameters: SqlParameter[] } {\n    const table = this.tableAlias;\n\n    let query = `SELECT ${!options.offsetLimit ? \"TOP @limit \" : \"\"}`;\n\n    // Add projection fields\n    query += this.generateProjectionFields(\n      searchType,\n      options.projectionMapping,\n      options.fullTextRankFilter,\n      options.withEmbedding\n    );\n\n    // Add FROM clause\n    query += ` FROM ${table}`;\n\n    // Add filterClause (WHERE clause) if provided\n    if (options.filterClause) {\n      if (typeof options.filterClause === \"string\") {\n        query += ` ${options.filterClause}`;\n      } else {\n        query += ` ${options.filterClause.query}`;\n      }\n    }\n\n    // Add ORDER BY clause based on search type\n    if (searchType === AzureCosmosDBNoSQLSearchType.FullTextRanking) {\n      if (options?.fullTextRankFilter?.length === 1) {\n        const item = options.fullTextRankFilter[0];\n        const terms = item.searchText\n          .split(\" \")\n          .map((_, termIndex) => `@${item.searchField}_0_term_${termIndex}`)\n          .join(\", \");\n        query += ` ORDER BY RANK FullTextScore(${table}[@${item.searchField}], ${terms})`;\n      } else {\n        const rankComponents = options?.fullTextRankFilter?.map(\n          (item, filterIndex) => {\n            const terms = item.searchText\n              .split(\" \")\n              .map(\n                (_, termIndex) =>\n                  `@${item.searchField}_${filterIndex}_term_${termIndex}`\n              )\n              .join(\", \");\n            return `FullTextScore(${table}[@${item.searchField}], ${terms})`;\n          }\n        );\n        query += ` ORDER BY RANK RRF(${rankComponents?.join(\", \")})`;\n      }\n    } else if (\n      searchType === AzureCosmosDBNoSQLSearchType.Vector ||\n      searchType === AzureCosmosDBNoSQLSearchType.VectorScoreThreshold\n    ) {\n      query += ` ORDER BY VectorDistance(${table}[@embeddingKey], @embeddings)`;\n    } else if (\n      searchType === AzureCosmosDBNoSQLSearchType.Hybrid ||\n      searchType === AzureCosmosDBNoSQLSearchType.HybridScoreThreshold\n    ) {\n      const rankComponents = options?.fullTextRankFilter?.map(\n        (item, filterIndex) => {\n          const terms = item.searchText\n            .split(\" \")\n            .map(\n              (_, termIndex) =>\n                `@${item.searchField}_${filterIndex}_term_${termIndex}`\n            )\n            .join(\", \");\n          return `FullTextScore(${table}[@${item.searchField}], ${terms})`;\n        }\n      );\n\n      query += ` ORDER BY RANK RRF(${rankComponents?.join(\n        \", \"\n      )}, VectorDistance(${table}[@embeddingKey], @embeddings)`;\n      if (options.weights) {\n        query += \", @weights)\";\n      } else {\n        query += \")\";\n      }\n    }\n\n    // Add offset/limit if provided\n    if (options.offsetLimit) {\n      query += ` ${options.offsetLimit}`;\n    }\n\n    const parameters = this.buildParameters(\n      k,\n      searchType,\n      options.embeddings,\n      options.projectionMapping,\n      options.fullTextRankFilter,\n      options.weights,\n      options.filterClause\n    );\n\n    return { query, parameters };\n  }\n\n  /**\n   * Generates the SELECT clause projection fields for the SQL query.\n   */\n  private generateProjectionFields(\n    searchType: AzureCosmosDBNoSQLSearchType,\n    projectionMapping?: ProjectionMapping,\n    fullTextRankFilter?: AzureCosmosDBNoSQLFullTextRankFilter[],\n    withEmbedding?: boolean\n  ): string {\n    const table = this.tableAlias;\n    let projection = \"\";\n    let isDefaultProjectionRequired = true;\n\n    if (projectionMapping) {\n      const fields = Object.entries(projectionMapping).map(\n        ([key, alias]) => `${table}[@${key}] as ${alias}`\n      );\n\n      if (fields.length > 0) {\n        projection += fields.join(\", \");\n        isDefaultProjectionRequired = false;\n      }\n    }\n\n    if (fullTextRankFilter) {\n      if (isDefaultProjectionRequired) {\n        projection = `${table}.id, ${table}[@metadataKey] as ${this.metadataKey}`;\n      }\n      const fields: string[] = [];\n      const addedSearchFields = new Set<string>();\n      fullTextRankFilter.forEach((item) => {\n        if (\n          !projectionMapping ||\n          !Object.keys(projectionMapping).includes(item.searchField)\n        ) {\n          if (!addedSearchFields.has(item.searchField)) {\n            fields.push(\n              `${table}[@${item.searchField}] as ${item.searchField}`\n            );\n            addedSearchFields.add(item.searchField);\n          }\n        }\n      });\n      if (fields.length > 0) {\n        projection += `, ${fields.join(\", \")}`;\n      }\n    } else {\n      if (isDefaultProjectionRequired) {\n        projection = `${table}.id, ${table}[@textKey] as ${this.textKey}, ${table}[@metadataKey] as ${this.metadataKey}`;\n      }\n    }\n\n    if (\n      searchType === AzureCosmosDBNoSQLSearchType.Vector ||\n      searchType === AzureCosmosDBNoSQLSearchType.VectorScoreThreshold ||\n      searchType === AzureCosmosDBNoSQLSearchType.Hybrid ||\n      searchType === AzureCosmosDBNoSQLSearchType.HybridScoreThreshold\n    ) {\n      if (withEmbedding) {\n        projection += `, ${table}[@embeddingKey] as ${this.embeddingKey}`;\n      }\n      projection += `, VectorDistance(${table}[@embeddingKey], @embeddings) as SimilarityScore`;\n    }\n\n    return projection;\n  }\n\n  /**\n   * Builds the parameter array for the SQL query.\n   */\n  private buildParameters(\n    k: number,\n    searchType: AzureCosmosDBNoSQLSearchType,\n    embeddings?: number[],\n    projectionMapping?: ProjectionMapping,\n    fullTextRankFilter?: AzureCosmosDBNoSQLFullTextRankFilter[],\n    weights?: number[],\n    filterClause?: AzureCosmosDBNoSQLQueryFilter\n  ): SqlParameter[] {\n    const parameters: SqlParameter[] = [{ name: \"@limit\", value: k }];\n    let isDefaultParamRequired = true;\n\n    // Add filterClause parameters if it's a SqlQuerySpec\n    if (filterClause && typeof filterClause !== \"string\") {\n      if (filterClause.parameters) {\n        parameters.push(...filterClause.parameters);\n      }\n    }\n\n    const addedFieldParams = new Set<string>();\n\n    if (projectionMapping) {\n      isDefaultParamRequired = false;\n      Object.keys(projectionMapping).forEach((key) => {\n        if (!addedFieldParams.has(key)) {\n          parameters.push({ name: `@${key}`, value: key });\n          addedFieldParams.add(key);\n        }\n      });\n    }\n\n    if (\n      searchType === AzureCosmosDBNoSQLSearchType.Vector ||\n      searchType === AzureCosmosDBNoSQLSearchType.VectorScoreThreshold ||\n      searchType === AzureCosmosDBNoSQLSearchType.Hybrid ||\n      searchType === AzureCosmosDBNoSQLSearchType.HybridScoreThreshold\n    ) {\n      parameters.push({\n        name: \"@embeddingKey\",\n        value: this.embeddingKey,\n      });\n      if (embeddings) {\n        parameters.push({ name: \"@embeddings\", value: embeddings });\n      }\n      if (weights) {\n        parameters.push({ name: \"@weights\", value: weights });\n      }\n    }\n\n    if (fullTextRankFilter) {\n      if (isDefaultParamRequired) {\n        parameters.push({ name: \"@metadataKey\", value: this.metadataKey });\n      }\n      isDefaultParamRequired = false;\n      fullTextRankFilter.forEach((item, filterIndex) => {\n        if (!addedFieldParams.has(item.searchField)) {\n          parameters.push({\n            name: `@${item.searchField}`,\n            value: item.searchField,\n          });\n          addedFieldParams.add(item.searchField);\n        }\n        item.searchText.split(\" \").forEach((term, termIndex) => {\n          parameters.push({\n            name: `@${item.searchField}_${filterIndex}_term_${termIndex}`,\n            value: term,\n          });\n        });\n      });\n    }\n\n    if (isDefaultParamRequired) {\n      parameters.push({\n        name: \"@textKey\",\n        value: this.textKey,\n      });\n      parameters.push({ name: \"@metadataKey\", value: this.metadataKey });\n    }\n\n    return parameters;\n  }\n\n  /**\n   * Extracts the text content from a query result item.\n   * Uses custom projection mapping alias if provided, otherwise falls back to the default textKey.\n   */\n  private extractTextFromItem(\n    item: Record<string, unknown>,\n    projectionMapping?: ProjectionMapping\n  ): string {\n    if (projectionMapping && this.textKey in projectionMapping) {\n      const textKey = projectionMapping[this.textKey];\n      return item[textKey] as string;\n    }\n    return item[this.textKey] as string;\n  }\n\n  /**\n   * Populates metadata object from query result item fields.\n   * Adds projected field aliases to metadata, or defaults to adding the document id.\n   */\n  private populateMetadataFromItem(\n    item: Record<string, unknown>,\n    baseMetadata: Record<string, unknown>,\n    projectionMapping?: ProjectionMapping\n  ): Record<string, unknown> {\n    if (projectionMapping) {\n      for (const [key, alias] of Object.entries(projectionMapping)) {\n        if (key !== this.textKey) {\n          baseMetadata[alias] = item[alias];\n        }\n      }\n    } else {\n      baseMetadata.id = item.id;\n    }\n    return baseMetadata;\n  }\n\n  /**\n   * Executes a Cosmos DB SQL query and transforms the results into Documents with scores.\n   * Runs the query against the container, processes the returned items,\n   * applies threshold filtering if specified, and constructs Document objects with metadata.\n   *\n   * @param query The SQL query string to execute.\n   * @param searchType The type of search being performed, which affects result processing.\n   * @param parameters The query parameters to bind to the SQL query.\n   * @param options Execution options including threshold filtering, embedding inclusion, and projection mapping.\n   * @returns A promise that resolves to an array of tuples containing Documents and their scores.\n   */\n  private async executeQuery(\n    query: string,\n    searchType: AzureCosmosDBNoSQLSearchType,\n    parameters: SqlParameter[],\n    options: {\n      withEmbedding?: boolean;\n      projectionMapping?: ProjectionMapping;\n      threshold?: number;\n    }\n  ): Promise<[Document, number][]> {\n    await this.initialize();\n\n    const { resources: items } = await this.container.items\n      .query({ query, parameters }, { forceQueryPlan: true })\n      .fetchAll();\n\n    const threshold = options.threshold ?? 0;\n    const isVectorSearch =\n      searchType === AzureCosmosDBNoSQLSearchType.Vector ||\n      searchType === AzureCosmosDBNoSQLSearchType.Hybrid ||\n      searchType === AzureCosmosDBNoSQLSearchType.VectorScoreThreshold ||\n      searchType === AzureCosmosDBNoSQLSearchType.HybridScoreThreshold;\n\n    const isThresholdSearch =\n      searchType === AzureCosmosDBNoSQLSearchType.VectorScoreThreshold ||\n      searchType === AzureCosmosDBNoSQLSearchType.HybridScoreThreshold;\n\n    const docsAndScores: [Document, number][] = [];\n\n    for (const item of items) {\n      const score = isVectorSearch ? item.SimilarityScore : 0;\n\n      // Skip items below threshold for threshold-based searches\n      if (isThresholdSearch && score <= threshold) {\n        continue;\n      }\n\n      const metadata: Record<string, unknown> = {\n        ...(item[this.metadataKey] || {}),\n      };\n\n      // Include embeddings if requested\n      if (isVectorSearch && options.withEmbedding) {\n        metadata[this.embeddingKey] = item[this.embeddingKey];\n      }\n\n      const text = this.extractTextFromItem(item, options.projectionMapping);\n      this.populateMetadataFromItem(item, metadata, options.projectionMapping);\n\n      docsAndScores.push([\n        new Document({\n          id: item.id,\n          pageContent: text,\n          metadata,\n        }),\n        score,\n      ]);\n    }\n\n    return docsAndScores;\n  }\n\n  /**\n   * Static method to create an instance of AzureCosmosDBNoSQLVectorStore from a\n   * list of texts. It first converts the texts to vectors and then adds\n   * them to the collection.\n   * @param texts List of texts to be converted to vectors.\n   * @param metadatas Metadata for the texts.\n   * @param embeddings Embeddings to be used for conversion.\n   * @param dbConfig Database configuration for Azure Cosmos DB for NoSQL.\n   * @returns Promise that resolves to a new instance of AzureCosmosDBNoSQLVectorStore.\n   */\n  static async fromTexts(\n    texts: string[],\n    metadatas: object[] | object,\n    embeddings: EmbeddingsInterface,\n    dbConfig: AzureCosmosDBNoSQLConfig\n  ): Promise<AzureCosmosDBNoSQLVectorStore> {\n    const docs: Document[] = [];\n    for (let i = 0; i < texts.length; i += 1) {\n      const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;\n      const newDoc = new Document({\n        pageContent: texts[i],\n        metadata,\n      });\n      docs.push(newDoc);\n    }\n    return AzureCosmosDBNoSQLVectorStore.fromDocuments(\n      docs,\n      embeddings,\n      dbConfig\n    );\n  }\n\n  /**\n   * Static method to create an instance of AzureCosmosDBNoSQLVectorStore from a\n   * list of documents. It first converts the documents to vectors and then\n   * adds them to the collection.\n   * @param docs List of documents to be converted to vectors.\n   * @param embeddings Embeddings to be used for conversion.\n   * @param dbConfig Database configuration for Azure Cosmos DB for NoSQL.\n   * @returns Promise that resolves to a new instance of AzureCosmosDBNoSQLVectorStore.\n   */\n  static async fromDocuments(\n    docs: Document[],\n    embeddings: EmbeddingsInterface,\n    dbConfig: AzureCosmosDBNoSQLConfig\n  ): Promise<AzureCosmosDBNoSQLVectorStore> {\n    const instance = new this(embeddings, dbConfig);\n    await instance.addDocuments(docs);\n    return instance;\n  }\n}\n"],"mappings":";;;;;;;;;AAyBA,MAAa,+BAA+B;CAE1C,QAAQ;CAER,sBAAsB;CAEtB,gBAAgB;CAEhB,iBAAiB;CAEjB,QAAQ;CAER,sBAAsB;CACvB;AAwID,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;AAwB1B,IAAa,gCAAb,MAAa,sCAAsCA,yCAAY;CAG7D,IAAI,aAAwC;AAC1C,SAAO,EACL,kBAAkB,0CACnB;;CAGH,AAAQ;CAER,AAAiB;CAEjB,AAAQ;CAER,AAAiB;CAEjB,AAAiB;CAEjB,AAAQ;CAER,AAAiB;CAEjB,AAAiB;CAEjB,AAAiB;CAEjB,AAAiB;;;;;;CAOjB;CAEA,mBAA2B;AACzB,SAAO;;CAGT,YACE,YACA,UACA;AACA,QAAM,YAAY,SAAS;EAE3B,MAAM,mBACJ,SAAS,0EACc,yCAAyC;EAElE,MAAM,WACJ,SAAS,kEACc,gCAAgC;AAEzD,MAAI,CAAC,SAAS,UAAU,CAAC,oBAAoB,CAAC,SAC5C,OAAM,IAAI,MACR,mFACD;AAGH,MAAI,CAAC,SAAS,OACZ,KAAI,iBACF,MAAK,SAAS,IAAIC,2BAAa;GAC7B;GACA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