### db.serve() Source: https://context7.com/jina-ai/vectordb/llms.txt Starts the database as a gRPC/HTTP/WebSocket service using Jina. Supports replicas and shards for scalability. ```APIDOC ## `db.serve()` — Serve the Database as a Network Service Starts the database as a gRPC/HTTP/WebSocket service using Jina. Returns a `Service` context manager; call `.block()` to keep it running, or use it directly as a context manager for in-process client-server testing. Supports `replicas` (≥ 3 for consensus) and `shards` for scalability. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import InMemoryExactNNVectorDB import numpy as np class DocSchema(BaseDoc): text: str = '' embedding: NdArray[128] db = InMemoryExactNNVectorDB[DocSchema](workspace='./serve_workspace') # Use as context manager for in-process service + client with db.serve(protocol='grpc', port=12345, replicas=1, shards=1) as service: # Index data directly through the service docs = DocList[DocSchema]([ DocSchema(text=f'doc {i}', embedding=np.random.rand(128)) for i in range(100) ]) service.index(inputs=docs) # Search via the service query = DocSchema(text='test', embedding=np.random.rand(128)) results = service.search(inputs=DocList[DocSchema]([query]), limit=5) print(f'Matches: {[m.text for m in results[0].matches]}') # To run as a long-lived server: # with db.serve(protocol='grpc', port=12345) as service: # service.block() ``` ``` -------------------------------- ### Install vectordb Source: https://github.com/jina-ai/vectordb/blob/main/README.md Install the vectordb package using pip. ```bash pip install vectordb ``` -------------------------------- ### Serve VectorDB as a Network Service using `db.serve()` Source: https://context7.com/jina-ai/vectordb/llms.txt Starts the database as a gRPC/HTTP/WebSocket service. Use as a context manager for in-process testing or call `.block()` for a long-lived server. Supports `replicas` and `shards` for scalability. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import InMemoryExactNNVectorDB import numpy as np class DocSchema(BaseDoc): text: str = '' embedding: NdArray[128] db = InMemoryExactNNVectorDB[DocSchema](workspace='./serve_workspace') # Use as context manager for in-process service + client with db.serve(protocol='grpc', port=12345, replicas=1, shards=1) as service: # Index data directly through the service docs = DocList[DocSchema]([ DocSchema(text=f'doc {i}', embedding=np.random.rand(128)) for i in range(100) ]) service.index(inputs=docs) # Search via the service query = DocSchema(text='test', embedding=np.random.rand(128)) results = service.search(inputs=DocList[DocSchema]([query]), limit=5) print(f'Matches: {[m.text for m in results[0].matches]}') # To run as a long-lived server: # with db.serve(protocol='grpc', port=12345) as service: # service.block() ``` -------------------------------- ### Scaling with Shards and Replicas Source: https://context7.com/jina-ai/vectordb/llms.txt Shards distribute the index across multiple workers, while replicas increase availability and search throughput. This example demonstrates serving with 3 replicas and 2 shards. ```APIDOC ## Scaling with Shards and Replicas Shards distribute the index across multiple workers to improve indexing throughput and reduce per-shard latency. Replicas (minimum 3 required for RAFT consensus) increase availability and search throughput. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import HNSWVectorDB import numpy as np class LargeDoc(BaseDoc): content: str = '' embedding: NdArray[256] db = HNSWVectorDB[LargeDoc](workspace='./scaled_workspace') # 3 replicas (RAFT consensus) x 2 shards = 6 executor instances # Requires replicas >= 3 for consensus, or exactly 1 with db.serve( protocol='grpc', port=12345, shards=2, replicas=3, ) as service: docs = DocList[LargeDoc]([ LargeDoc(content=f'item {i}', embedding=np.random.rand(256)) for i in range(10000) ]) service.index(inputs=docs) service.block() ``` ``` -------------------------------- ### Serve VectorDB as a gRPC Service Source: https://github.com/jina-ai/vectordb/blob/main/README.md Start the VectorDB service on a specified port using the gRPC protocol. The service will block until interrupted. ```python with db.serve(protocol='grpc', port=12345, replicas=1, shards=1) as service: service.block() ``` -------------------------------- ### Scaling VectorDB with Shards and Replicas Source: https://context7.com/jina-ai/vectordb/llms.txt Shards distribute the index for throughput and latency, while replicas (minimum 3 for RAFT consensus) increase availability and search throughput. This example demonstrates 3 replicas and 2 shards. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import HNSWVectorDB import numpy as np class LargeDoc(BaseDoc): content: str = '' embedding: NdArray[256] db = HNSWVectorDB[LargeDoc](workspace='./scaled_workspace') # 3 replicas (RAFT consensus) x 2 shards = 6 executor instances # Requires replicas >= 3 for consensus, or exactly 1 with db.serve( protocol='grpc', port=12345, shards=2, replicas=3, ) as service: docs = DocList[LargeDoc]([ LargeDoc(content=f'item {i}', embedding=np.random.rand(256)) for i in range(10000) ]) service.index(inputs=docs) service.block() ``` -------------------------------- ### HNSWVectorDB - Initialization, Indexing, and Batch Searching Source: https://context7.com/jina-ai/vectordb/llms.txt Shows how to initialize HNSWVectorDB with custom parameters, index documents, and perform batch searches. ```APIDOC ## HNSWVectorDB - Initialization, Indexing, and Batch Searching ### Description Initialize `HNSWVectorDB` with specific HNSW tuning parameters, index a `DocList` of documents, and then perform batch searches using multiple query documents. ### Method ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import HNSWVectorDB import numpy as np class ImageDoc(BaseDoc): label: str = '' embedding: NdArray[256] # Initialize with HNSW tuning parameters db = HNSWVectorDB[ImageDoc]( workspace='./hnsw_workspace', space='cosine', # 'l2' (default), 'ip', or 'cosine' max_elements=10000, # initial index capacity (grows dynamically) ef_construction=200, # build-time speed/accuracy trade-off ef=50, # query-time speed/accuracy trade-off M=16, # max outgoing graph connections allow_replace_deleted=True, num_threads=4, ) # Index documents docs = DocList[ImageDoc]([ ImageDoc(label=f'img_{i}', embedding=np.random.rand(256)) for i in range(5000) ]) db.index(inputs=docs) # Batch search: multiple queries at once queries = DocList[ImageDoc]([ ImageDoc(label='q1', embedding=np.random.rand(256)), ImageDoc(label='q2', embedding=np.random.rand(256)), ]) results = db.search(inputs=queries, limit=10) for i, res in enumerate(results): print(f'Query {i}: top match = {res.matches[0].label}') ``` ### Parameters #### Initialization - `workspace` (str): Path for persistence. - `space` (str): Distance space ('l2', 'ip', 'cosine'). Defaults to 'l2'. - `max_elements` (int): Initial index capacity. - `ef_construction` (int): Build-time speed/accuracy trade-off. - `ef` (int): Query-time speed/accuracy trade-off. - `M` (int): Max outgoing graph connections. - `allow_replace_deleted` (bool): Whether to allow replacing deleted elements. - `num_threads` (int): Number of threads to use for indexing/searching. #### Indexing - `inputs` (DocList[Schema]): A list of documents to index. #### Searching - `inputs` (DocList[Schema]): A list of query documents. - `limit` (int): The maximum number of nearest neighbors to return. ``` -------------------------------- ### Serve VectorDB Locally via CLI Source: https://github.com/jina-ai/vectordb/blob/main/README.md Use the `vectordb serve` command to make your database accessible locally. Ensure you specify the database to serve. ```bash vectordb serve --db example:db ``` -------------------------------- ### Deploy VectorDB to Jina AI Cloud Source: https://context7.com/jina-ai/vectordb/llms.txt Deploy a database instance to Jina AI Cloud. Requires prior login using `jc login`. ```bash jc login vectordb deploy --db example:db --protocol grpc --shards 1 ``` -------------------------------- ### Connect to VectorDB Service with `Client` Source: https://context7.com/jina-ai/vectordb/llms.txt Connects to a running VectorDB service and exposes the same `index`, `search`, `update`, and `delete` methods as the local database object. Ensure the server is running and accessible at the specified address. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import Client import numpy as np class DocSchema(BaseDoc): text: str = '' embedding: NdArray[128] # Connect to a running server (replace address as needed) client = Client[DocSchema](address='grpc://0.0.0.0:12345') # Index documents client.index(inputs=DocList[DocSchema]([ DocSchema(text=f'remote doc {i}', embedding=np.random.rand(128)) for i in range(50) ])) # Search query = DocSchema(text='find me', embedding=np.random.rand(128)) results = client.search(inputs=DocList[DocSchema]([query]), limit=3) for match in results[0].matches: print(match.text) # Update a document client.update(inputs=DocList[DocSchema]([ DocSchema(id='some-known-id', text='updated text', embedding=np.random.rand(128)) ])) # Delete a document client.delete(inputs=DocList[DocSchema]([ DocSchema(id='some-known-id', embedding=np.zeros(128)) ])) ``` -------------------------------- ### Initialize InMemoryExactNNVectorDB Source: https://github.com/jina-ai/vectordb/blob/main/README.md Initialize an InMemoryExactNNVectorDB with a specified Document schema and workspace path. ```python from docarray import DocList import numpy as np from vectordb import InMemoryExactNNVectorDB, HNSWVectorDB # Specify your workspace path db = InMemoryExactNNVectorDB[ToyDoc](workspace='./workspace_path') ``` -------------------------------- ### Serve VectorDB with Multiple Protocols and Ports Source: https://context7.com/jina-ai/vectordb/llms.txt Configure VectorDB to serve on multiple protocols and ports simultaneously for flexible access. ```bash vectordb serve --db example:db --port 8081,8082 --protocol grpc,http ``` -------------------------------- ### Connect to VectorDB Service Client Source: https://github.com/jina-ai/vectordb/blob/main/README.md Instantiate a client connected to a running VectorDB service. Replace '0.0.0.0' with the server's IP address in practice. ```python from vectordb import Client client = Client[ToyDoc](address='grpc://0.0.0.0:12345') results = client.search(inputs=DocList[ToyDoc]([query]), limit=10) ``` -------------------------------- ### InMemoryExactNNVectorDB - Indexing and Searching Source: https://context7.com/jina-ai/vectordb/llms.txt Demonstrates how to initialize InMemoryExactNNVectorDB, index documents, and perform nearest-neighbor searches. ```APIDOC ## InMemoryExactNNVectorDB - Indexing and Searching ### Description Initialize `InMemoryExactNNVectorDB` with a workspace path, index a `DocList` of documents, and then perform a search to find the nearest neighbors to a query vector. ### Method ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import InMemoryExactNNVectorDB import numpy as np class TextDoc(BaseDoc): text: str = '' embedding: NdArray[128] # 128-dimensional float vector # Initialize with a workspace directory for persistence db = InMemoryExactNNVectorDB[TextDoc](workspace='./my_workspace') # Index 1000 documents docs = DocList[TextDoc]([ TextDoc(text=f'document {i}', embedding=np.random.rand(128)) for i in range(1000) ]) db.index(inputs=docs) # Search: find 5 nearest neighbors to a query vector query = TextDoc(text='query', embedding=np.random.rand(128)) results = db.search(inputs=DocList[TextDoc]([query]), limit=5) # results[0].matches contains the top-5 nearest documents for match in results[0].matches: print(match.text, match.scores) ``` ### Parameters #### Indexing - `inputs` (DocList[Schema]): A list of documents to index. #### Searching - `inputs` (DocList[Schema]): A list of query documents. - `limit` (int): The maximum number of nearest neighbors to return. ``` -------------------------------- ### Deploy VectorDB on Jina AI Cloud via CLI Source: https://github.com/jina-ai/vectordb/blob/main/README.md Use the `vectordb deploy` command to deploy your database on Jina AI Cloud. Specify the database to deploy. ```bash vectordb deploy --db example:db ``` -------------------------------- ### Manage Deployed VectorDB Instances with jcloud Source: https://github.com/jina-ai/vectordb/blob/main/README.md Manage your deployed VectorDB instances using the `jcloud` command-line tool. Available commands include list, pause, resume, and remove. ```bash jcloud list ID jcloud pause ID or jcloud resume ID jcloud remove ID ``` -------------------------------- ### Serve VectorDB using CLI `vectordb serve` Source: https://context7.com/jina-ai/vectordb/llms.txt Serve a database object defined in a Python module without writing a script. This command-line interface allows for quick deployment of a VectorDB instance. ```bash vectordb serve --module my_module --class MyVectorDB --port 12345 ``` -------------------------------- ### Deploy VectorDB Instance to Jina AI Cloud Source: https://github.com/jina-ai/vectordb/blob/main/README.md Deploy a local VectorDB instance to Jina AI Cloud using the `vectordb deploy` command. This makes your database accessible from any location. ```bash jc login vectordb deploy --db example:db ``` -------------------------------- ### Configure InMemoryExactNNVectorDB Source: https://github.com/jina-ai/vectordb/blob/main/README.md Instantiate and serve an in-memory VectorDB. Specify the document type and the workspace for data persistence. ```python InMemoryExactNNVectorDB[MyDoc](workspace='./vectordb') ``` ```python InMemoryExactNNVectorDB[MyDoc].serve(workspace='./vectordb') ``` -------------------------------- ### Multi-Protocol Serving (gRPC + HTTP + WebSocket) Source: https://context7.com/jina-ai/vectordb/llms.txt VectorDB can serve multiple protocols simultaneously by providing lists to `protocol` and `port`. Ensure each protocol has a corresponding port specified. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import InMemoryExactNNVectorDB import numpy as np class Doc(BaseDoc): text: str = '' embedding: NdArray[64] db = InMemoryExactNNVectorDB[Doc](workspace='./multi_proto_ws') with db.serve( protocol=['grpc', 'http', 'websocket'], port=[12345, 12346, 12347], replicas=1, shards=1, ) as service: service.block() # gRPC available on 12345, HTTP on 12346, WebSocket on 12347 ``` -------------------------------- ### Embed and Serve VectorDB Instance for Cloud Deployment Source: https://github.com/jina-ai/vectordb/blob/main/README.md Embed a VectorDB instance or class into a Python file for deployment. Ensure the serving part is protected by a `if __name__ == '__main__':` guard. ```python # example.py from docarray import BaseDoc from vectordb import InMemoryExactNNVectorDB db = InMemoryExactNNVectorDB[ToyDoc](workspace='./vectordb') # notice how `db` is the instance that we want to serve if __name__ == '__main__': # IMPORTANT: make sure to protect this part of the code using __main__ guard with db.serve() as service: service.block() ``` -------------------------------- ### Connect to Deployed VectorDB Instance Source: https://github.com/jina-ai/vectordb/blob/main/README.md Connect to a VectorDB instance deployed on Jina AI Cloud using the `vectordb` Client. Replace 'ID' with the actual ID of your deployed DB. ```python from vectordb import Client # replace the ID with the ID of your deployed DB as shown in the screenshot above c = Client(address='grpcs://ID.wolf.jina.ai') ``` -------------------------------- ### HNSWVectorDB - Index and Search Source: https://context7.com/jina-ai/vectordb/llms.txt Initialize an HNSW approximate nearest-neighbor vector database with tuning parameters, index documents, and perform batch searches. Results are sorted by L2 distance by default. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import HNSWVectorDB import numpy as np class ImageDoc(BaseDoc): label: str = '' embedding: NdArray[256] # Initialize with HNSW tuning parameters db = HNSWVectorDB[ImageDoc]( workspace='./hnsw_workspace', space='cosine', # 'l2' (default), 'ip', or 'cosine' max_elements=10000, # initial index capacity (grows dynamically) ef_construction=200, # build-time speed/accuracy trade-off ef=50, # query-time speed/accuracy trade-off M=16, # max outgoing graph connections allow_replace_deleted=True, num_threads=4, ) # Index documents docs = DocList[ImageDoc]([ ImageDoc(label=f'img_{i}', embedding=np.random.rand(256)) for i in range(5000) ]) db.index(inputs=docs) # Batch search: multiple queries at once queries = DocList[ImageDoc]([ ImageDoc(label='q1', embedding=np.random.rand(256)), ImageDoc(label='q2', embedding=np.random.rand(256)), ]) results = db.search(inputs=queries, limit=10) for i, res in enumerate(results): print(f'Query {i}: top match = {res.matches[0].label}') ``` -------------------------------- ### InMemoryExactNNVectorDB - Index and Search Source: https://context7.com/jina-ai/vectordb/llms.txt Initialize an in-memory vector database, index documents, and perform nearest-neighbor searches. Results are sorted by cosine similarity. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import InMemoryExactNNVectorDB import numpy as np class TextDoc(BaseDoc): text: str = '' embedding: NdArray[128] # Initialize with a workspace directory for persistence db = InMemoryExactNNVectorDB[TextDoc](workspace='./my_workspace') # Index 1000 documents docs = DocList[TextDoc]([ TextDoc(text=f'document {i}', embedding=np.random.rand(128)) for i in range(1000) ]) db.index(inputs=docs) # Search: find 5 nearest neighbors to a query vector query = TextDoc(text='query', embedding=np.random.rand(128)) results = db.search(inputs=DocList[TextDoc]([query]), limit=5) # results[0].matches contains the top-5 nearest documents for match in results[0].matches: print(match.text, match.scores) # Expected output (example): # document 472 [0.9821] # document 13 [0.9803] # ... ``` -------------------------------- ### Perform Similarity Search with `db.search()` Source: https://context7.com/jina-ai/vectordb/llms.txt Accepts a DocList of query documents and returns the same list enriched with `.matches` and `.scores` attributes sorted by relevance. The `limit` parameter controls how many nearest neighbors are returned per query. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import HNSWVectorDB import numpy as np class ArticleDoc(BaseDoc): title: str = '' embedding: NdArray[128] db = HNSWVectorDB[ArticleDoc](workspace='./articles_db') # Build index db.index(inputs=DocList[ArticleDoc]([ ArticleDoc(title=f'Article {i}', embedding=np.random.rand(128)) for i in range(500) ])) # Single-document query (automatically wrapped into DocList) query = ArticleDoc(title='search query', embedding=np.random.rand(128)) results = db.search(inputs=DocList[ArticleDoc]([query]), limit=3) print(f'Found {len(results[0].matches)} matches') for match, score in zip(results[0].matches, results[0].scores): print(f' {match.title} score={score:.4f}') # Example output: # Found 3 matches # Article 142 score=0.0312 # Article 77 score=0.0389 # Article 301 score=0.0421 ``` -------------------------------- ### Multi-Protocol Serving Source: https://context7.com/jina-ai/vectordb/llms.txt VectorDB can serve gRPC, HTTP, and WebSocket protocols simultaneously by passing a list to `protocol` and a matching list to `port`. ```APIDOC ## Multi-Protocol Serving (gRPC + HTTP + WebSocket) VectorDB can serve all three protocols simultaneously by passing a list to `protocol` and a matching list to `port`. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import InMemoryExactNNVectorDB import numpy as np class Doc(BaseDoc): text: str = '' embedding: NdArray[64] db = InMemoryExactNNVectorDB[Doc](workspace='./multi_proto_ws') with db.serve( protocol=['grpc', 'http', 'websocket'], port=[12345, 12346, 12347], replicas=1, shards=1, ) as service: service.block() # gRPC available on 12345, HTTP on 12346, WebSocket on 12347 ``` ``` -------------------------------- ### Index Documents with `db.index()` Source: https://context7.com/jina-ai/vectordb/llms.txt Adds a DocList of documents to the vector index. Documents receive a unique `id` automatically if one is not provided; track these IDs if you need to delete or update specific documents later. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import InMemoryExactNNVectorDB import numpy as np class ProductDoc(BaseDoc): name: str = '' price: float = 0.0 embedding: NdArray[64] db = InMemoryExactNNVectorDB[ProductDoc](workspace='./products_db') products = DocList[ProductDoc]([ ProductDoc(name='Widget A', price=9.99, embedding=np.random.rand(64)), ProductDoc(name='Widget B', price=19.99, embedding=np.random.rand(64)), ProductDoc(name='Gadget X', price=49.99, embedding=np.random.rand(64)), ]) db.index(inputs=products) print(f'Indexed {db.num_docs()} documents') # Output: Indexed {'num_docs': 3} ``` -------------------------------- ### Retrieve Document by ID using `db.get_by_id()` Source: https://context7.com/jina-ai/vectordb/llms.txt Fetches a single document from the index by its exact ID. Returns `None` if the ID does not exist. Ensure the `RecordDoc` schema and the database are initialized. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import InMemoryExactNNVectorDB import numpy as np class RecordDoc(BaseDoc): label: str = '' embedding: NdArray[16] db = InMemoryExactNNVectorDB[RecordDoc](workspace='./records_db') doc = RecordDoc(id='record-42', label='special record', embedding=np.random.rand(16)) db.index(inputs=DocList[RecordDoc]([doc])) found = db.get_by_id('record-42') print(found.label) # special record missing = db.get_by_id('does-not-exist') print(missing) # None ``` -------------------------------- ### Index and Search Documents with Embeddings Source: https://github.com/jina-ai/vectordb/blob/main/README.md Index a list of documents with random embeddings and perform a search query. The search results are available in the `.matches` attribute. ```python doc_list = [ToyDoc(text=f'toy doc {i}', embedding=np.random.rand(128)) for i in range(1000)] db.index(inputs=DocList[ToyDoc](doc_list)) query = ToyDoc(text='query', embedding=np.random.rand(128)) results = db.search(inputs=DocList[ToyDoc]([query]), limit=10) for m in results[0].matches: print(m) ``` -------------------------------- ### Manually Persist In-Memory Index to Disk Source: https://context7.com/jina-ai/vectordb/llms.txt Force an immediate flush of the in-memory index to disk. Ensure the workspace directory exists. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import InMemoryExactNNVectorDB import numpy as np class Doc(BaseDoc): embedding: NdArray[32] db = InMemoryExactNNVectorDB[Doc](workspace='./persist_ws') db.index(inputs=DocList[Doc]([Doc(embedding=np.random.rand(32)) for _ in range(100)])) # Explicitly flush to disk db.persist() # Data is now safe in ./persist_ws/index.bin ``` -------------------------------- ### Client Source: https://context7.com/jina-ai/vectordb/llms.txt Remote Client for a Running VectorDB Service. Connects to a running VectorDB service and exposes the same index, search, update, and delete methods as the local database object. ```APIDOC ## `Client` — Remote Client for a Running VectorDB Service `Client[Schema]` connects to a running VectorDB service and exposes the same `index`, `search`, `update`, and `delete` methods as the local database object. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import Client import numpy as np class DocSchema(BaseDoc): text: str = '' embedding: NdArray[128] # Connect to a running server (replace address as needed) client = Client[DocSchema](address='grpc://0.0.0.0:12345') # Index documents client.index(inputs=DocList[DocSchema]([ DocSchema(text=f'remote doc {i}', embedding=np.random.rand(128)) for i in range(50) ])) # Search query = DocSchema(text='find me', embedding=np.random.rand(128)) results = client.search(inputs=DocList[DocSchema]([query]), limit=3) for match in results[0].matches: print(match.text) # Update a document client.update(inputs=DocList[DocSchema]([ DocSchema(id='some-known-id', text='updated text', embedding=np.random.rand(128)) ])) # Delete a document client.delete(inputs=DocList[DocSchema]([ DocSchema(id='some-known-id', embedding=np.zeros(128)) ])) ``` ``` -------------------------------- ### db.search() — Similarity Search Source: https://context7.com/jina-ai/vectordb/llms.txt Accepts a DocList of query documents (or a single BaseDoc) and returns the same list enriched with .matches and .scores attributes sorted by relevance. The limit parameter controls how many nearest neighbors are returned per query. ```APIDOC ## `db.search()` — Similarity Search Accepts a `DocList` of query documents (or a single `BaseDoc`) and returns the same list enriched with `.matches` and `.scores` attributes sorted by relevance. The `limit` parameter controls how many nearest neighbors are returned per query. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import HNSWVectorDB import numpy as np class ArticleDoc(BaseDoc): title: str = '' embedding: NdArray[128] db = HNSWVectorDB[ArticleDoc](workspace='./articles_db') # Build index db.index(inputs=DocList[ArticleDoc]([ ArticleDoc(title=f'Article {i}', embedding=np.random.rand(128)) for i in range(500) ])) # Single-document query (automatically wrapped into DocList) query = ArticleDoc(title='search query', embedding=np.random.rand(128)) results = db.search(inputs=DocList[ArticleDoc]([query]), limit=3) print(f'Found {len(results[0].matches)} matches') for match, score in zip(results[0].matches, results[0].scores): print(f' {match.title} score={score:.4f}') # Example output: # Found 3 matches # Article 142 score=0.0312 # Article 77 score=0.0389 # Article 301 score=0.0421 ``` ``` -------------------------------- ### db.index() — Index Documents Source: https://context7.com/jina-ai/vectordb/llms.txt Adds a DocList of documents to the vector index. Documents receive a unique id automatically if one is not provided; track these IDs if you need to delete or update specific documents later. ```APIDOC ## `db.index()` — Index Documents Adds a `DocList` of documents to the vector index. Documents receive a unique `id` automatically if one is not provided; track these IDs if you need to delete or update specific documents later. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import InMemoryExactNNVectorDB import numpy as np class ProductDoc(BaseDoc): name: str = '' price: float = 0.0 embedding: NdArray[64] db = InMemoryExactNNVectorDB[ProductDoc](workspace='./products_db') products = DocList[ProductDoc]([ ProductDoc(name='Widget A', price=9.99, embedding=np.random.rand(64)), ProductDoc(name='Widget B', price=19.99, embedding=np.random.rand(64)), ProductDoc(name='Gadget X', price=49.99, embedding=np.random.rand(64)), ]) db.index(inputs=products) print(f'Indexed {db.num_docs()} documents') # Output: Indexed {'num_docs': 3} ``` ``` -------------------------------- ### Count Indexed Documents with `db.num_docs()` Source: https://context7.com/jina-ai/vectordb/llms.txt Returns the total number of documents currently stored in the index. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import HNSWVectorDB import numpy as np class Vec(BaseDoc): embedding: NdArray[16] db = HNSWVectorDB[Vec](workspace='./count_db') db.index(inputs=DocList[Vec]([Vec(embedding=np.random.rand(16)) for _ in range(42)])) count = db.num_docs() print(count) # {'num_docs': 42} ``` -------------------------------- ### db.get_by_id() Source: https://context7.com/jina-ai/vectordb/llms.txt Fetches a single document from the index by its exact ID. Returns None if the ID does not exist. ```APIDOC ## `db.get_by_id()` — Retrieve Document by ID Fetches a single document from the index by its exact `id`. Returns `None` if the ID does not exist. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import InMemoryExactNNVectorDB import numpy as np class RecordDoc(BaseDoc): label: str = '' embedding: NdArray[16] db = InMemoryExactNNVectorDB[RecordDoc](workspace='./records_db') doc = RecordDoc(id='record-42', label='special record', embedding=np.random.rand(16)) db.index(inputs=DocList[RecordDoc]([doc])) found = db.get_by_id('record-42') print(found.label) # special record missing = db.get_by_id('does-not-exist') print(missing) # None ``` ``` -------------------------------- ### Define Document Schema with DocArray Source: https://github.com/jina-ai/vectordb/blob/main/README.md Define a Document schema using DocArray's BaseDoc and typing for embeddings. ```python from docarray import BaseDoc from docarray.typing import NdArray class ToyDoc(BaseDoc): text: str = '' embedding: NdArray[128] ``` -------------------------------- ### Delete Documents with `db.delete()` Source: https://context7.com/jina-ai/vectordb/llms.txt Removes documents from the index by their `id`. Only the `id` field is required on the provided `DocList`; other fields are ignored. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import InMemoryExactNNVectorDB import numpy as np class NoteDoc(BaseDoc): content: str = '' embedding: NdArray[32] db = InMemoryExactNNVectorDB[NoteDoc](workspace='./notes_db') docs = DocList[NoteDoc]([ NoteDoc(id='note-1', content='First note', embedding=np.random.rand(32)), NoteDoc(id='note-2', content='Second note', embedding=np.random.rand(32)), NoteDoc(id='note-3', content='Third note', embedding=np.random.rand(32)), ]) db.index(inputs=docs) print(db.num_docs()) # {'num_docs': 3} # Delete by ID — only the id field matters to_delete = DocList[NoteDoc]([NoteDoc(id='note-2', embedding=np.zeros(32))]) db.delete(inputs=to_delete) print(db.num_docs()) # {'num_docs': 2} ``` -------------------------------- ### Update Documents with `db.update()` Source: https://context7.com/jina-ai/vectordb/llms.txt Replaces indexed documents that share the same `id` with updated field values. Only the `id` field is used for matching; all other fields are overwritten. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import InMemoryExactNNVectorDB import numpy as np class ItemDoc(BaseDoc): name: str = '' embedding: NdArray[32] db = InMemoryExactNNVectorDB[ItemDoc](workspace='./items_db') # Index original documents original = DocList[ItemDoc]([ ItemDoc(id='doc-001', name='Old Name A', embedding=np.random.rand(32)), ItemDoc(id='doc-002', name='Old Name B', embedding=np.random.rand(32)), ]) db.index(inputs=original) # Update doc-001 with a new name and new embedding updated = DocList[ItemDoc]([ ItemDoc(id='doc-001', name='New Name A', embedding=np.random.rand(32)), ]) db.update(inputs=updated) # Verify result = db.get_by_id('doc-001') print(result.name) # Output: New Name A ``` -------------------------------- ### db.num_docs() — Count Indexed Documents Source: https://context7.com/jina-ai/vectordb/llms.txt Returns the total number of documents currently stored in the index. ```APIDOC ## `db.num_docs()` — Count Indexed Documents Returns the total number of documents currently stored in the index. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import HNSWVectorDB import numpy as np class Vec(BaseDoc): embedding: NdArray[16] db = HNSWVectorDB[Vec](workspace='./count_db') db.index(inputs=DocList[Vec]([Vec(embedding=np.random.rand(16)) for _ in range(42)])) count = db.num_docs() print(count) # {'num_docs': 42} ``` ``` -------------------------------- ### db.update() — Update Documents Source: https://context7.com/jina-ai/vectordb/llms.txt Replaces indexed documents that share the same id with updated field values. Only the id field is used for matching; all other fields are overwritten. ```APIDOC ## `db.update()` — Update Documents Replaces indexed documents that share the same `id` with updated field values. Only the `id` field is used for matching; all other fields are overwritten. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import InMemoryExactNNVectorDB import numpy as np class ItemDoc(BaseDoc): name: str = '' embedding: NdArray[32] db = InMemoryExactNNVectorDB[ItemDoc](workspace='./items_db') # Index original documents original = DocList[ItemDoc]([ ItemDoc(id='doc-001', name='Old Name A', embedding=np.random.rand(32)), ItemDoc(id='doc-002', name='Old Name B', embedding=np.random.rand(32)), ]) db.index(inputs=original) # Update doc-001 with a new name and new embedding updated = DocList[ItemDoc]([ ItemDoc(id='doc-001', name='New Name A', embedding=np.random.rand(32)), ]) db.update(inputs=updated) # Verify result = db.get_by_id('doc-001') print(result.name) # Output: New Name A ``` ``` -------------------------------- ### db.delete() — Delete Documents Source: https://context7.com/jina-ai/vectordb/llms.txt Removes documents from the index by their id. Only the id field is required on the provided DocList; other fields are ignored. ```APIDOC ## `db.delete()` — Delete Documents Removes documents from the index by their `id`. Only the `id` field is required on the provided `DocList`; other fields are ignored. ```python from docarray import DocList, BaseDoc from docarray.typing import NdArray from vectordb import InMemoryExactNNVectorDB import numpy as np class NoteDoc(BaseDoc): content: str = '' embedding: NdArray[32] db = InMemoryExactNNVectorDB[NoteDoc](workspace='./notes_db') docs = DocList[NoteDoc]([ NoteDoc(id='note-1', content='First note', embedding=np.random.rand(32)), NoteDoc(id='note-2', content='Second note', embedding=np.random.rand(32)), NoteDoc(id='note-3', content='Third note', embedding=np.random.rand(32)), ]) db.index(inputs=docs) print(db.num_docs()) # {'num_docs': 3} # Delete by ID — only the id field matters to_delete = DocList[NoteDoc]([NoteDoc(id='note-2', embedding=np.zeros(32))]) db.delete(inputs=to_delete) print(db.num_docs()) # {'num_docs': 2} ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.