-
Notifications
You must be signed in to change notification settings - Fork 2.9k
feat(): add elasticsearch hybrid search #9385
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
margaretjgu
wants to merge
10
commits into
langchain-ai:main
Choose a base branch
from
margaretjgu:hybrid_elasticsearch
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
f735940
define hybrid class
margaretjgu a4ab670
add strategy, user agent
margaretjgu d868ba3
add lexical
margaretjgu cfeea39
add rrf retriever
margaretjgu 9001bec
tests for default
margaretjgu 3950bb6
tests for default
margaretjgu c28160b
tests
margaretjgu 73246de
docs and examples
margaretjgu f0383b6
remove 9.2 compliance
margaretjgu 9e26a6b
remove 9.2 compliance
margaretjgu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
123 changes: 123 additions & 0 deletions
123
examples/src/langchain-classic/indexes/vector_stores/elasticsearch/elasticsearch_hybrid.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| import { Client, ClientOptions } from "@elastic/elasticsearch"; | ||
| import { OpenAIEmbeddings } from "@langchain/openai"; | ||
| import { | ||
| ElasticClientArgs, | ||
| ElasticVectorSearch, | ||
| HybridRetrievalStrategy, | ||
| } from "@langchain/community/vectorstores/elasticsearch"; | ||
| import { Document } from "@langchain/core/documents"; | ||
|
|
||
| /** | ||
| * Demonstrates hybrid search with Elasticsearch, combining: | ||
| * - Vector (semantic) search using embeddings | ||
| * - BM25 (lexical) full-text search | ||
| * - Reciprocal Rank Fusion (RRF) for result merging | ||
| * | ||
| * Requirements: | ||
| * - Elasticsearch 8.9+ (for RRF support) | ||
| * - Run: docker-compose up -d --build (in elasticsearch directory) | ||
| * - Set ELASTIC_URL, ELASTIC_API_KEY (or ELASTIC_USERNAME/ELASTIC_PASSWORD) | ||
| */ | ||
| export async function run() { | ||
| const config: ClientOptions = { | ||
| node: process.env.ELASTIC_URL ?? "http://127.0.0.1:9200", | ||
| }; | ||
| if (process.env.ELASTIC_API_KEY) { | ||
| config.auth = { | ||
| apiKey: process.env.ELASTIC_API_KEY, | ||
| }; | ||
| } else if (process.env.ELASTIC_USERNAME && process.env.ELASTIC_PASSWORD) { | ||
| config.auth = { | ||
| username: process.env.ELASTIC_USERNAME, | ||
| password: process.env.ELASTIC_PASSWORD, | ||
| }; | ||
| } | ||
|
|
||
| const embeddings = new OpenAIEmbeddings(); | ||
|
|
||
| const clientArgs: ElasticClientArgs = { | ||
| client: new Client(config), | ||
| indexName: process.env.ELASTIC_INDEX ?? "test_hybrid_search", | ||
| strategy: new HybridRetrievalStrategy({ | ||
| rankWindowSize: 100, | ||
| rankConstant: 60, | ||
| textField: "text", | ||
| }), | ||
| }; | ||
|
|
||
| const vectorStore = new ElasticVectorSearch(embeddings, clientArgs); | ||
|
|
||
| await vectorStore.deleteIfExists(); | ||
|
|
||
| // Add sample documents | ||
| const docs = [ | ||
| new Document({ | ||
| pageContent: "Running helps build cardiovascular endurance and strengthens leg muscles.", | ||
| metadata: { category: "fitness", topic: "running" }, | ||
| }), | ||
| new Document({ | ||
| pageContent: "Marathon training requires consistent mileage and proper recovery.", | ||
| metadata: { category: "fitness", topic: "running" }, | ||
| }), | ||
| new Document({ | ||
| pageContent: "Muscle soreness after exercise is caused by microscopic damage to muscle fibers.", | ||
| metadata: { category: "health", topic: "recovery" }, | ||
| }), | ||
| new Document({ | ||
| pageContent: "Stretching and foam rolling can help prevent post-workout muscle pain.", | ||
| metadata: { category: "health", topic: "recovery" }, | ||
| }), | ||
| new Document({ | ||
| pageContent: "Python is a popular programming language for data science and machine learning.", | ||
| metadata: { category: "technology", topic: "programming" }, | ||
| }), | ||
| ]; | ||
|
|
||
| console.log("Adding documents to Elasticsearch..."); | ||
| await vectorStore.addDocuments(docs); | ||
| console.log("Documents added successfully!\n"); | ||
|
|
||
| // Example 1: Hybrid search combines semantic + keyword matching | ||
| console.log("=== Example 1: Hybrid Search ==="); | ||
| const query1 = "How to avoid muscle soreness while running?"; | ||
| console.log(`Query: "${query1}"\n`); | ||
|
|
||
| const results1 = await vectorStore.similaritySearchWithScore(query1, 3); | ||
| results1.forEach(([doc, score], i) => { | ||
| console.log(`${i + 1}. [Score: ${score.toFixed(4)}] ${doc.pageContent}`); | ||
| console.log(` Metadata: ${JSON.stringify(doc.metadata)}\n`); | ||
| }); | ||
|
|
||
| // Example 2: Semantic search works well for conceptual queries | ||
| console.log("\n=== Example 2: Semantic Query ==="); | ||
| const query2 = "tips for preventing pain after workouts"; | ||
| console.log(`Query: "${query2}"\n`); | ||
|
|
||
| const results2 = await vectorStore.similaritySearchWithScore(query2, 2); | ||
| results2.forEach(([doc, score], i) => { | ||
| console.log(`${i + 1}. [Score: ${score.toFixed(4)}] ${doc.pageContent}`); | ||
| console.log(` Metadata: ${JSON.stringify(doc.metadata)}\n`); | ||
| }); | ||
|
|
||
| // Example 3: With metadata filters | ||
| console.log("\n=== Example 3: Hybrid Search with Filters ==="); | ||
| const query3 = "fitness advice"; | ||
| console.log(`Query: "${query3}"`); | ||
| console.log(`Filter: category = "fitness"\n`); | ||
|
|
||
| const results3 = await vectorStore.similaritySearchWithScore( | ||
| query3, | ||
| 3, | ||
| { category: "fitness" } | ||
| ); | ||
| results3.forEach(([doc, score], i) => { | ||
| console.log(`${i + 1}. [Score: ${score.toFixed(4)}] ${doc.pageContent}`); | ||
| console.log(` Metadata: ${JSON.stringify(doc.metadata)}\n`); | ||
| }); | ||
|
|
||
| // Clean up | ||
| console.log("\n=== Cleanup ==="); | ||
| await vectorStore.deleteIfExists(); | ||
| console.log("Index deleted."); | ||
| } | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
default value inferred from the
VectorStoreclass that we extend fromlangchainjs/libs/langchain-core/src/vectorstores.ts
Lines 661 to 671 in 87f120b