-
Notifications
You must be signed in to change notification settings - Fork 4
Add bulk_embed_and_insert_texts #3
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
Merged
Merged
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
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 |
---|---|---|
@@ -1,3 +1,4 @@ | ||
.idea/ | ||
.DS_STORE | ||
__pycache__/ | ||
.env |
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
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,62 @@ | ||
"""Tests for CRUD utilities.""" | ||
|
||
|
||
from collections.abc import Callable, Generator, Iterable | ||
from typing import Any | ||
|
||
from bson import ObjectId | ||
from pymongo import ReplaceOne | ||
from pymongo.synchronous.collection import Collection | ||
|
||
from pymongo_vectorsearch_utils.util import oid_to_str, str_to_oid | ||
|
||
|
||
def bulk_embed_and_insert_texts( | ||
texts: list[str] | Iterable[str], | ||
metadatas: list[dict] | Generator[dict, Any, Any], | ||
embedding_func: Callable[[list[str]], list[list[float]]], | ||
collection: Collection[Any], | ||
text_key: str, | ||
embedding_key: str, | ||
ids: list[str] | None = None, | ||
**kwargs: Any, | ||
) -> list[str]: | ||
"""Bulk insert single batch of texts, embeddings, and optionally ids. | ||
Important notes on ids: | ||
- If _id or id is a key in the metadatas dicts, one must | ||
pop them and provide as separate list. | ||
- They must be unique. | ||
- If they are not provided, unique ones are created, | ||
stored as bson.ObjectIds internally, and strings in the database. | ||
These will appear in Document.metadata with key, '_id'. | ||
Args: | ||
texts: Iterable of strings to add to the vectorstore. | ||
metadatas: Optional list of metadatas associated with the texts. | ||
embedding_func: A function that generates embedding vectors from the texts. | ||
collection: The MongoDB collection where documents will be inserted. | ||
text_key: The field name where thet text will be stored in each document. | ||
embedding_key: The field name where the embedding will be stored in each document. | ||
ids: Optional list of unique ids that will be used as index in VectorStore. | ||
See note on ids. | ||
""" | ||
if not texts: | ||
return [] | ||
# Compute embedding vectors | ||
embeddings = embedding_func(list(texts)) | ||
if not ids: | ||
ids = [str(ObjectId()) for _ in range(len(list(texts)))] | ||
docs = [ | ||
{ | ||
"_id": str_to_oid(i), | ||
text_key: t, | ||
embedding_key: embedding, | ||
**m, | ||
} | ||
for i, t, m, embedding in zip(ids, texts, metadatas, embeddings, strict=False) | ||
] | ||
operations = [ReplaceOne({"_id": doc["_id"]}, doc, upsert=True) for doc in docs] | ||
# insert the documents in MongoDB Atlas | ||
result = collection.bulk_write(operations) | ||
assert result.upserted_ids is not None | ||
return [oid_to_str(_id) for _id in result.upserted_ids.values()] |
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,44 @@ | ||
import logging | ||
from typing import Any | ||
|
||
logger = logging.getLogger(__file__) | ||
|
||
|
||
def str_to_oid(str_repr: str) -> Any | str: | ||
"""Attempt to cast string representation of id to MongoDB's internal BSON ObjectId. | ||
|
||
To be consistent with ObjectId, input must be a 24 character hex string. | ||
If it is not, MongoDB will happily use the string in the main _id index. | ||
Importantly, the str representation that comes out of MongoDB will have this form. | ||
|
||
Args: | ||
str_repr: id as string. | ||
|
||
Returns: | ||
ObjectID | ||
""" | ||
from bson import ObjectId | ||
from bson.errors import InvalidId | ||
|
||
try: | ||
return ObjectId(str_repr) | ||
except InvalidId: | ||
logger.debug( | ||
"ObjectIds must be 12-character byte or 24-character hex strings. " | ||
"Examples: b'heres12bytes', '6f6e6568656c6c6f68656768'" | ||
) | ||
return str_repr | ||
|
||
|
||
def oid_to_str(oid: Any) -> str: | ||
"""Convert MongoDB's internal BSON ObjectId into a simple str for compatibility. | ||
|
||
Instructive helper to show where data is coming out of MongoDB. | ||
|
||
Args: | ||
oid: bson.ObjectId | ||
|
||
Returns: | ||
24 character hex string. | ||
""" | ||
return str(oid) |
Oops, something went wrong.
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.
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.
I don't think we need to export these two
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.
Don't we expect to use
bulk_embed_and_insert_texts
? Or do you mean the twostr_to_oid
andoid_to_str
?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.
str_to_oid and oid_to_str