AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

MongoDB Lgachein 統合を使い始める

注意

このチュートリアルでは、Lgachein のPythonライブラリ を使用します。JavaScriptライブラリを使用するチュートリアルについては、「 Lgachein JavaScript/ Typescript統合を使い始める 」を参照してください。

MongoDB ベクトル検索 をLgChuin と統合して、LM アプリケーションを構築し、検索拡張生成 (RAG)(RAG)を実装できます。 このチュートリアルでは、Lgachein とMongoDB ベクトル検索 の使用を開始し、データのセマンティック検索を実行し、RAG実装を構築する方法を説明します。具体的には、次のアクションを実行します。

  1. 環境を設定します。

  2. カスタム データをMongoDBに保存します。

  3. データにMongoDB ベクトル検索インデックスを作成します。

  4. 次のベクトル検索クエリを実行します。

    • セマンティック検索。

    • スコア付きのセマンティック検索。

    • メタデータの事前フィルタリングによるセマンティック検索。

  5. MongoDB ベクトル検索を使用してデータの質問に答え、RAG を実装します。

LgChuin は、「チェーン」の使用を通じて LVM アプリケーションの作成を簡素化するオープンソースのフレームワークです。チェーンは 、RAG を含むさまざまなAIユースケースで組み合わせることができる Lgachein 固有のコンポーネントです。

MongoDB ベクトル検索 をLgachein と統合することで、 MongoDB をベクトルデータベースとして使用し、 MongoDB ベクトル検索 を使用してセマンティックで類似したドキュメントを検索して RG を実装することができます。 RG の詳細については、 「 MongoDBによる検索拡張生成(RAG) 」を参照してください。

Atlas の サンプル データ セット からの映画データを含むコレクションを使用します。

このチュートリアルの環境を設定します。 .ipynb 拡張機能のファイルを保存して、インタラクティブPythonノートを作成します。 このノートはPythonコード スニペットを個別に実行でき、このチュートリアルのコードを実行するために使用します。

ノートク環境を設定するには、次の手順に従います。

1

次のコマンドを実行します:

pip install --quiet --upgrade langchain langchain-community langchain-core langchain-mongodb langchain-voyageai langchain-openai langchain-text-splitters pymongo pypdf

次に、次のコードを実行して必要なパッケージをインポートします。

import os, pymongo, pprint
from langchain_community.document_loaders import PyPDFLoader
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain_mongodb import MongoDBAtlasVectorSearch
from langchain_voyageai import VoyageAIEmbeddings
from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain_text_splitters import RecursiveCharacterTextSplitter
from pymongo import MongoClient
from pymongo.operations import SearchIndexModel
2

次のコードを実行し、プレースホルダーを次の値に置き換えます。

  • 投票AIと OpenAI APIキー

  • MongoDBクラスターの接続文字列。

os.environ["VOYAGE_API_KEY"] = "<voyage-api-key>"
os.environ["OPENAI_API_KEY"] = "<openai-api-key>"
MONGODB_URI = "<connection-string>"

注意

<connection-string> を Atlas クラスターまたはローカル Atlas 配置の接続文字列に置き換えます。

接続stringには、次の形式を使用する必要があります。

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

重要:接続文字列にデータベースユーザーの認証情報が含まれていることを確認します。接続文字列の検索方法の詳細については、クライアント ライブラリ経由でクラスターに接続する を参照してください。

次に、カスタム データをMongoDBにロードし、 MongoDBクラスターをベクトルデータベースとしてインスタンス化します。これはベクトルストアとも呼ばれます。次のコード スニペットをコピーして、ノートに貼り付けます。

1

このチュートリアルでは、ベクトルストアのデータソースとして、最新のMongoDB収益レポートに関する一般にアクセス可能な PDFドキュメントを使用します。

サンプル データをロードするには、次のコード スニペットを実行します。 この処理では、次の処理が行われます。

  • 指定された URL から PDF を検索し、未加工のテキスト データを読み込みます。

  • テキストスプリット を使用して、データを小さなドキュメントに分裂。

  • 各ドキュメントの文字数と連続する 2 つのドキュメント間で重複する文字数を決定する チャンク パラメータを指定します。

# Load the PDF
loader = PyPDFLoader("https://investors.mongodb.com/node/13176/pdf")
data = loader.load()
# Split PDF into documents
text_splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=20)
docs = text_splitter.split_documents(data)
# Print the first document
docs[0]
Document(metadata={'producer': 'West Corporation using ABCpdf', 'creator': 'PyPDF', 'creationdate': '2025-03-05T21:06:26+00:00', 'title': 'MongoDB, Inc. Announces Fourth Quarter and Full Year Fiscal 2025 Financial Results', 'source': 'https://investors.mongodb.com/node/13176/pdf', 'total_pages': 9, 'page': 0, 'page_label': '1'}, page_content='MongoDB, Inc. Announces Fourth Quarter and Full Year Fiscal 2025 Financial Results\nMarch 5, 2025\nFourth Quarter Fiscal 2025 Total Revenue of $548.4 million, up 20% Year-over-Year')
2

次のコードを実行して、サンプル ドキュメントから vector_store という名前のベクトル ストア インスタンスを作成します。このスニペットによって次の内容が指定されます。

  • MongoDBクラスターへの接続文字列。

  • langchain_db.test は、ドキュメントを保存するためのMongoDB名前空間です。

  • Vyage AIの voyage-3-large 埋め込みモデル。テキストを embeddingフィールドのベクトル埋め込みに変換する。

  • vector_index ベクトル ストアをクエリするために使用するインデックスとして 。

# Instantiate the vector store using your MongoDB connection string
vector_store = MongoDBAtlasVectorSearch.from_connection_string(
connection_string = MONGODB_URI,
namespace = "langchain_db.test",
embedding = VoyageAIEmbeddings(model="voyage-3-large"),
index_name = "vector_index"
)
# Add documents to the vector store
vector_store.add_documents(documents=docs)

Atlaslangchain_db.test を使用している場合は、サンプルコードの実行中後、Atlas UIの 名前空間に移動することでベクトル埋め込みを検証できます。

ベクトルストアでベクトル検索クエリを有効にするには、L SheinヘルパーメソッドまたはPyMongoドライバー メソッドを使用して、langchain_db.testコレクションにMongoDB ベクトル検索インデックスを作成します。

ノートブックで次のコードを、お好みの方法で実行します。インデックス定義では、次のフィールドのインデックス作成を指定します。

  • embedding ベクトル型としてのフィールド。 embeddingフィールドには、Voyage AI のvoyage-3-large 埋め込みモデルを使用して作成された埋め込みが含まれます。インデックス定義では、1024 ベクトル次元を指定し、cosine を使用して類似性を測定します。

  • page_label PDF 内のページ番号でデータを事前にフィルタリングするためのフィルター タイプとしてのフィールド。

# Use helper method to create the vector search index
vector_store.create_vector_search_index(
dimensions = 1024, # The number of vector dimensions to index
filters = [ "page_label" ]
)

インデックスの構築には約 1 分かかります。構築中、インデックスは最初の同期状態になります。構築が完了したら、コレクション内のデータのクエリを開始できます。

MongoDB がインデックスを構築 したら、データに対してベクトル検索クエリを実行します。次の例は、ベクトル化されたデータに対して実行できるさまざまなクエリを示しています。

Tip

セマンティック検索メソッドの完全なリストについては、 API リファレンスを参照してください。

このセクションでは、 MongoDB ベクトル検索と Lgachein を使用してアプリケーションに RG を実装する方法を説明します。 MongoDB ベクトル検索 を使用してセマンティックに類似したドキュメントを検索したので、次のコード例を実行して、それらのドキュメントに基づいて質問に答えるように LM に指示します。

この例では、次の処理を行います。

  • MongoDB ベクトル検索 k10を検索するための検索バーとしてインスタンス化します。これには、最も関連性の高いドキュメントのみを検索するための任意の パラメーターも含まれます。
  • これらのドキュメントをクエリのコンテキストとして使用するように LM に指示する Lgachein プロンプト テンプレートを定義します。 LgChart はこれらのドキュメントを 入力変数に渡し、クエリを{context} {question}変数に渡します。

  • 次の内容を指定するチェーンを構築します。

    • コンテキストとして使用するドキュメントを検索するためのリージョンとしてのMongoDB ベクトル検索 。

    • 定義した プロンプト テンプレート。

    • コンテキストに応じた応答を生成する OpenAI の gpt-4o チャットモデル。

  • サンプル クエリを使用してチェーンを呼び出します。

  • LM の応答とコンテキストとして使用されたドキュメントを返します。生成される応答は異なる場合があります。

# Instantiate MongoDB Vector Search as a retriever
retriever = vector_store.as_retriever(
search_type = "similarity",
search_kwargs = { "k": 10 }
)
# Define a prompt template
template = """
Use the following pieces of context to answer the question at the end.
{context}
Question: {question}
"""
prompt = PromptTemplate.from_template(template)
model = ChatOpenAI(model="gpt-4o")
# Construct a chain to answer questions on your data
chain = (
{ "context": retriever, "question": RunnablePassthrough()}
| prompt
| model
| StrOutputParser()
)
# Prompt the chain
question = "What was MongoDB's latest acquisition?"
answer = chain.invoke(question)
print("Question: " + question)
print("Answer: " + answer)
# Return source documents
documents = retriever.invoke(question)
print("\nSource documents:")
pprint.pprint(documents)
Question: What was MongoDB's latest acquisition?
Answer: MongoDB's latest acquisition was Voyage AI, a pioneer in state-of-the-art embedding and reranking models.
Source documents:
[Document(id='67f0259b8bb2babc06924409', metadata={'_id': '67f0259b8bb2babc06924409', ... 'page_label': '9'}, page_content='SOURCE MongoDB, Inc.'),
Document(id='67f0259b8bb2babc06924351', metadata={'_id': '67f0259b8bb2babc06924351', ... 'page_label': '2'}, page_content='Measures."\nFourth Quarter Fiscal 2025 and Recent Business Highlights\nMongoDB acquired Voyage AI, a pioneer in state-of-the-art embedding and reranking models that power next-generation'),
Document(id='67f0259b8bb2babc0692432f', metadata={'_id': '67f0259b8bb2babc0692432f', ... 'page_label': '1'}, page_content='MongoDB platform. In fiscal year 2026 we expect to see stable consumption growth in Atlas, our main growth driver," said Dev Ittycheria, President\nand Chief Executive Officer of MongoDB .'),
Document(id='67f0259b8bb2babc06924355', metadata={'_id': '67f0259b8bb2babc06924355', ... 'page_label': '2'}, page_content='conjunction with the acquisition of Voyage, MongoDB is announcing a stock buyback program of $200 million, to offset the\ndilutive impact of the acquisition consideration.'),
Document(id='67f0259b8bb2babc069243a6', metadata={'_id': '67f0259b8bb2babc069243a6', ... 'page_label': '4'}, page_content="MongoDB's unified, intelligent data platform was built to power the next generation of applications, and MongoDB is the most widely available, globally"),
Document(id='67f0259b8bb2babc06924329', metadata={'_id': '67f0259b8bb2babc06924329', ... 'page_label': '1'}, page_content='MongoDB, Inc. Announces Fourth Quarter and Full Year Fiscal 2025 Financial Results\nMarch 5, 2025\nFourth Quarter Fiscal 2025 Total Revenue of $548.4 million, up 20% Year-over-Year'),
Document(id='67f0259b8bb2babc069243a7', metadata={'_id': '67f0259b8bb2babc069243a7', ... 'page_label': '4'}, page_content='distributed database on the market. With integrated capabilities for operational data, search, real-time analytics, and AI-powered retrieval, MongoDB'),
Document(id='67f0259b8bb2babc069243a5', metadata={'_id': '67f0259b8bb2babc069243a5', ... 'page_label': '4'}, page_content="Headquartered in New York, MongoDB's mission is to empower innovators to create, transform, and disrupt industries with software and data."),
Document(id='67f0259b8bb2babc06924354', metadata={'_id': '67f0259b8bb2babc06924354', ... 'page_label': '2'}, page_content='data.\nMongoDB completed the redemption of 2026 Convertible Notes, eliminating all debt from the balance sheet. Additionally, in'),
Document(id='67f0259b8bb2babc069243a9', metadata={'_id': '67f0259b8bb2babc069243a9', ... 'page_label': '4'}, page_content='50,000 customers across almost every industry—including 70% of the Fortune 100—rely on MongoDB for their most important applications. To learn\nmore, visit mongodb.com .\nInvestor Relations')]

このビデオチュートリアルで、LangChain と MongoDB を使用したセマンティック検索および RAG について詳しく学べます。

所要時間: 8分