Skip to main content
Semantic Search
Richa Deshpande avatar
Written by Richa Deshpande
Updated over 7 months ago

Vector Search queries power semantic search. Semantic search is a powerful data searching technique which uses the intent and contextual meaning behind a search query to deliver more relevant results.

The following query uses the similarity_search method to perform a basic semantic search for the string MongoDB Atlas security. It returns a list of documents ranked by relevance. Make sure you've added a vector data store and vector search index first.

Install libraries:

pip install --upgrade langchain langchain-mongodb langchain-openai pymongo pypdf 

Code Sample:

import 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_openai import ChatOpenAI, OpenAIEmbeddings
from langchain.prompts import PromptTemplate
from langchain.text_splitter import RecursiveCharacterTextSplitter
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi

# Create the MongoDB Atlas Vector Search instance
vector_search = MongoDBAtlasVectorSearch.from_connection_string(
connection_string = uri,
namespace = “langchain_db.test”,
embedding = embeddings,
index_name=“vector_index_test”,
)

# Insert the documents into the vector store
vector_search.add_documents(docs)

# Use the similarity_search method to perform a basic similarity search
question = "MongoDB Atlas security"
results = vector_search.similarity_search(question)

pprint.pprint(results)

The output shows relevant results that semantically match the intent behind the question “MongoDB Atlas security”. Try out different questions to test the outputs. Try more advanced features like scoring and filtering with these examples.

Did this answer your question?