> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lambdadb.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Start with an SDK

> Get started with LambdaDB in minutes. Create a collection and retrieve its documents with full-text and vector search.

To connect a coding agent first, see [Start with an AI agent](https://docs.lambdadb.ai/guides/get-started/with-an-agent.md).

This guide walks you through getting a **project API key**, installing an SDK, creating your first searchable knowledge collection, and running hybrid search queries. You'll store source documents with text, keyword, and dense vector fields, then combine lexical matching with vector similarity to retrieve relevant knowledge.

## 🔑 Step 1: Create your API key

You'll use a **project API key** from **[LambdaDB Cloud](https://app.lambdadb.ai)** starting in Step 3.

> [!NOTE]
>
> **LambdaDB Cloud** is in **public preview**.

Project creation and management are available through LambdaDB Cloud. The
public API and SDK documentation starts with an existing project.

1. **Sign in to LambdaDB Cloud** — Open [app.lambdadb.ai](https://app.lambdadb.ai), sign up if needed, and sign in.

2. **Create a project** — Accounts without a payment method are on the **Free** plan. Choose an AWS region that fits your latency or data-residency needs.

3. **Create a project API key** — Project creation does not automatically create an API key. Once the project is ready, open its **API Keys** tab, select **Create key** (or **Create your first key**), enter a name, and create the key.

4. **Save the key and connection details** — The full key value is shown only once, immediately after key creation. Store it securely, then use it with the project's **base URL** and **project name** from the console starting in Step 3.

### Manage API keys

Organization **Owners** and **Admins** can create and revoke project API keys in the **API Keys** tab. If you cannot create a key, ask an Owner or Admin. The key list does not reveal saved key values; if you lose a value, create a replacement key.

To replace a key, create a new one, update your application's credentials, and verify that it works before revoking the old key. Revocation cannot be undone and applications still using the revoked key will lose access. Key management is available through LambdaDB Cloud, not the public data API or SDKs documented here.

> [!NOTE]
>
> LambdaDB Cloud uses region-specific API base URLs. Use your project's **base URL** and **project name**, together with a **project API key** created in its **API Keys** tab. Project creation does not automatically issue a key; save the full value when you create it, because it is shown only once. See [API key management](https://docs.lambdadb.ai/guides/get-started/quickstart.md#manage-api-keys). Do not assume a global default URL or a fixed project name.

> [!NOTE]
>
> The Free plan includes monthly read, write, storage, and inference usage at no cost. Add a payment method when you need Pay as You Go usage beyond the Free plan limits. See [Understanding costs](https://docs.lambdadb.ai/guides/costs/understanding-costs.md).

> [!TIP]
>
> The Cloud console also supports loading data and running queries in the GUI, alongside the SDK examples in this guide.

> [!NOTE]
>
> Keep your API key out of source control and prefer environment variables instead of hardcoding it in scripts.

## 🚀 Step 2: Install the SDK

Install the latest stable SDK for your language. See [SDK support](https://docs.lambdadb.ai/reference/sdk/introduction.md#supported-sdk-versions) for supported releases and runtime requirements. Pin a version in your application for reproducible builds.

```bash Python theme={null}
pip install --upgrade lambdadb
```

```bash TypeScript theme={null}
npm install @functional-systems/lambdadb@latest
```

```bash Go theme={null}
go get github.com/lambdadb/go-lambdadb@latest
```

> [!TIP]
>
> Python SDK 0.15.0 requires Python 3.10–3.13; use a virtual environment to keep dependencies separate. Go SDK 0.9.0 requires Go 1.22 or later. Check the selected release for its runtime requirements.

## 📚 Step 3: Create a collection

A [collection](https://docs.lambdadb.ai/guides/collections/collection-overview.md) is where you store documents, embeddings, and metadata, and define how each field is indexed for retrieval. LambdaDB supports 9 different [index types](https://docs.lambdadb.ai/guides/collections/index-types.md): text, keyword, long, double, boolean, object, datetime, dense vector, and sparse vector.

Let's [create a collection](https://docs.lambdadb.ai/guides/collections/create-a-collection.md) that combines text search with vector similarity:

Run the steps in order using one language. Python steps open a new client context for each operation and reuse `collection_name`. TypeScript steps reuse the initialized client. For Go, append the later snippets inside `main`, before its closing brace, using the imports shown in Step 3. Replace all connection placeholders before running.

```python Python theme={null}
from lambdadb import LambdaDB

# Initialize the LambdaDB client with the base URL and project name from your LambdaDB Cloud project
with LambdaDB(
    project_api_key="your_api_key_here",
    base_url="YOUR_BASE_URL",
    project_name="YOUR_PROJECT_NAME",
) as client:
    collection_name = "your_collection_name_here"
    res = client.collections.create(
        collection_name=collection_name,
        index_configs={
            "text": {
                "type": "text",
                "analyzers": ["english", "korean"],
            },
            "keyword": {"type": "keyword"},
            "vector": {
                "type": "vector",
                "dimensions": 64,
                "similarity": "cosine",
            },
        },
    )
    print(res)
```

> [!NOTE]
>
> Python: `LambdaDB` supports context manager usage. `__enter__` returns the client, and `__exit__` calls `client.close()` (closing the SDK-owned HTTP client) and makes the client unusable after the `with` block. If you don't use `with`, call `client.close()` when you're done. If you pass a custom `client=`/`async_client=`, you own closing it.

```typescript TypeScript theme={null}
import { LambdaDBClient } from "@functional-systems/lambdadb";

// Initialize the LambdaDB client with the base URL and project name from your LambdaDB Cloud project
const client = new LambdaDBClient({
  projectApiKey: "your_api_key_here",
  baseUrl: "YOUR_BASE_URL",
  projectName: "YOUR_PROJECT_NAME",
});
const collectionName = "your_collection_name_here";
const createResult = await client.createCollection({
  collectionName,
  indexConfigs: {
    text: { type: "text", analyzers: ["english", "korean"] },
    keyword: { type: "keyword" },
    vector: { type: "vector", dimensions: 64, similarity: "cosine" },
  },
});
console.log(createResult);
```

```go Go theme={null}
package main

import (
  "context"
  "fmt"
  "log"
  lambdadb "github.com/lambdadb/go-lambdadb"
  "github.com/lambdadb/go-lambdadb/models/components"
)

func main() {
  ctx := context.Background()
  client := lambdadb.New(
    lambdadb.WithBaseURL("YOUR_BASE_URL"),
    lambdadb.WithProjectName("YOUR_PROJECT_NAME"),
    lambdadb.WithAPIKey("your_api_key_here"),
  )
  collectionName := "your_collection_name_here"
  createResult, err := client.Collections.Create(ctx, lambdadb.CreateCollectionOptions{
    CollectionName: collectionName,
    IndexConfigs: map[string]components.IndexConfigsUnion{
      "text": components.CreateIndexConfigsUnionText(components.IndexConfigsText{
        Type: components.TypeTextText,
        Analyzers: []components.Analyzer{components.AnalyzerEnglish, components.AnalyzerKorean},
      }),
      "keyword": components.CreateIndexConfigsUnionKeyword(components.IndexConfigs{Type: components.TypeKeyword}),
      "vector": components.CreateIndexConfigsUnionVector(components.IndexConfigsVector{
        Type: components.TypeVectorVector,
        Dimensions: 64,
        Similarity: components.SimilarityCosine.ToPointer(),
      }),
    },
  })
  if err != nil {
    log.Fatal(err)
  }
  fmt.Printf("%+v\n", createResult)
}
```

The underlying REST response is `201 Created` and includes the default branch:

```json theme={null}
{
  "collection": {
    "collectionName": "your_collection_name_here",
    "description": "",
    "tags": {},
    "defaultBranchName": "main",
    "snapshotRetentionInDays": 30,
    "createdAt": 1788336000000
  }
}
```

**Key configuration details:**

* **Text field**: This example selects English and Korean analyzers from the 49 fixed presets. Both process every value; language is not detected automatically. [Choose text analyzers](https://docs.lambdadb.ai/guides/collections/choose-text-analyzers.md) explains how to select and combine presets for your data.
* **Vector field**: Synthetic 64-dimensional vectors using cosine similarity. For real embeddings, match the model's dimensions and [similarity requirements](https://docs.lambdadb.ai/guides/collections/index-types.md#supported-similarity-metrics).
* **Keyword field**: Added to support [exact match filtering](https://docs.lambdadb.ai/guides/search/query-string.md#exact-keyword-match).

To have LambdaDB generate embeddings from your text or images, choose a [native embedding configuration](https://docs.lambdadb.ai/guides/collections/native-embeddings.md#collection-schema) when creating the collection. That flow writes the source fields instead of direct vector values and searches with `knn.queryText` or `knn.queryInputs`; LambdaDB manages provider credentials. The examples below use caller-provided vectors.

`201 Created` confirms collection creation, not query-serving readiness. If a subsequent operation encounters a loading or transient error, follow [Errors and retries](https://docs.lambdadb.ai/reference/api/introduction.md#errors-and-retries); do not recreate the collection to wait for readiness.

## 📄 Step 4: Add documents

Now let's [upsert some sample documents](https://docs.lambdadb.ai/guides/documents/upsert-data.md). Each document contains text for full-text search, keywords for filtering, and vectors for similarity search:

```python Python theme={null}
with LambdaDB(project_api_key="your_api_key_here", base_url="YOUR_BASE_URL", project_name="YOUR_PROJECT_NAME") as client:
    coll = client.collection(collection_name)
    docs = [
        {"id": "doc1", "text": "Serverless computing does not mean no servers are involved. It refers to a cloud computing model where the server management is abstracted away from developers.", "keyword": "serverless", "vector": [(i + 1) / 64 for i in range(64)]},
        {"id": "doc2", "text": "Instead, it refers to a cloud computing model where developers can build and run applications without having to manage the underlying infrastructure.", "keyword": "cloud", "vector": [(i + 2) / 64 for i in range(64)]},
        {"id": "doc3", "text": "The key aspect is that developers don't need to explicitly provision or manage servers. The cloud provider handles all server management automatically.", "keyword": ["serverless", "infrastructure"], "vector": [(i + 3) / 64 for i in range(64)]},
    ]
    res = coll.docs.upsert(docs=docs)
    print(res)
```

```typescript TypeScript theme={null}
const collection = client.collection(collectionName);
const docs = [
  { id: "doc1", text: "Serverless computing does not mean no servers are involved. It refers to a cloud computing model where the server management is abstracted away from developers.", keyword: "serverless", vector: Array.from({ length: 64 }, (_, i) => (i + 1) / 64) },
  { id: "doc2", text: "Instead, it refers to a cloud computing model where developers can build and run applications without having to manage the underlying infrastructure.", keyword: "cloud", vector: Array.from({ length: 64 }, (_, i) => (i + 2) / 64) },
  { id: "doc3", text: "The key aspect is that developers don't need to explicitly provision or manage servers. The cloud provider handles all server management automatically.", keyword: ["serverless", "infrastructure"], vector: Array.from({ length: 64 }, (_, i) => (i + 3) / 64) },
];
const upsertResult = await collection.docs.upsert({ docs });
console.log(upsertResult);
```

```go Go theme={null}
coll := client.Collection(collectionName)
demoVector := func(offset int) []float64 {
  values := make([]float64, 64)
  for i := range values { values[i] = float64(i + offset) / 64 }
  return values
}
docs := []map[string]interface{}{
  {"id": "doc1", "text": "Serverless computing does not mean no servers are involved. It refers to a cloud computing model where the server management is abstracted away from developers.", "keyword": "serverless", "vector": demoVector(1)},
  {"id": "doc2", "text": "Instead, it refers to a cloud computing model where developers can build and run applications without having to manage the underlying infrastructure.", "keyword": "cloud", "vector": demoVector(2)},
  {"id": "doc3", "text": "The key aspect is that developers don't need to explicitly provision or manage servers. The cloud provider handles all server management automatically.", "keyword": []string{"serverless", "infrastructure"}, "vector": demoVector(3)},
}
upsertResult, err := coll.Docs().Upsert(ctx, lambdadb.UpsertDocsInput{Docs: docs})
if err != nil { log.Fatal(err) }
if upsertResult != nil && upsertResult.MessageResponse != nil {
  log.Printf("message: %s", upsertResult.MessageResponse.Message)
}
```

Response:

```python Python theme={null}
MessageResponse(message='Upsert request is accepted')
```

```typescript TypeScript theme={null}
{
    message: "Upsert request is accepted"
}
```

```go Go theme={null}
message: Upsert request is accepted
```

**Important notes:**

* **Upsert behavior**: Documents with the same ID will be replaced; new IDs create new documents. Use [partial updates](https://docs.lambdadb.ai/guides/documents/update-data.md) to change selected fields.
* **Auto-generated IDs**: If you don't provide an ID, one will be generated automatically.
* **Bulk operations**: For larger imports, see [Bulk upsert data](https://docs.lambdadb.ai/guides/documents/bulk-upsert-data.md). Collections with native embedding fields require regular upsert or update so LambdaDB can generate vectors.
* **Configurable consistency**: LambdaDB is eventually consistent by default, so there can be a slight delay before new or changed documents are visible to queries.
  If your application requires strong (read-after-write) consistency, set `consistentRead` (or `consistent_read` in Python) to `true` when querying or fetching a branch directly or through an alias that currently targets a branch. This overlays eligible pending writes, excluding pending bulk imports, and can return `429` if the pending payload exceeds its limit. Tag reads and an alias that targets a tag reject this option. See [Consistent reads](https://docs.lambdadb.ai/guides/data-versioning/branches-tags-aliases.md#consistent-reads) for the full contract.

**Check committed data:** The calls below show collection statistics. `numDocs` and `dataUpdatedAt` describe the default `main` branch's committed head; `dataUpdatedAt` may be absent before its first commit. To verify particular writes on any branch, query or fetch the expected records from that branch with `consistentRead: false`.

```python Python theme={null}
with LambdaDB(project_api_key="your_api_key_here", base_url="YOUR_BASE_URL", project_name="YOUR_PROJECT_NAME") as client:
    meta = client.collections.get(collection_name=collection_name)
    print(meta.collection)
```

```typescript TypeScript theme={null}
const meta = await client.collection(collectionName).get();
console.log(meta);
```

```go Go theme={null}
meta, err := client.Collection(collectionName).Get(ctx)
if err != nil { log.Fatal(err) }
_ = meta
```

## 🔍 Step 5: Full-text search

Let's use [query string search](https://docs.lambdadb.ai/guides/search/query-string.md) to find documents that match "I hate managing servers" while filtering for documents tagged exactly with "serverless". In this [Boolean query](https://docs.lambdadb.ai/guides/search/boolean.md#occur), the text clause is required, and the keyword filter restricts results without contributing to the score:

```python Python theme={null}
with LambdaDB(project_api_key="your_api_key_here", base_url="YOUR_BASE_URL", project_name="YOUR_PROJECT_NAME") as client:
    coll = client.collection(collection_name)
    res = coll.query(
        size=10,
        query={
            "bool": [
                {"queryString": {"query": "I hate managing servers", "defaultField": "text"}, "occur": "must"},
                {"queryString": {"query": "keyword:serverless"}, "occur": "filter"},
            ]
        },
        consistent_read=True,
    )
    print("🔍 Search Results:")
    # Query responses expose items in `res.docs` (each item includes `doc` and `score`).
    # Use `res.documents` if you want document bodies only (no scores).
    for item in res.docs:
        doc_id = str(item.doc.get("id"))
        score = f"{item.score:.2f}" if item.score is not None else "n/a"
        keyword = str(item.doc.get("keyword"))
        text = str(item.doc.get("text", ""))[:60]
        print(f"{doc_id:<5} | {score:<5} | {keyword:<15} | {text}...")
```

```typescript TypeScript theme={null}
const fullTextResult = await collection.query({
  size: 10,
  query: {
    bool: [
      { queryString: { query: "I hate managing servers", defaultField: "text" }, occur: "must" },
      { queryString: { query: "keyword:serverless" }, occur: "filter" },
    ],
  },
  consistentRead: true,
});
console.log("🔍 Search Results:");
for (const item of fullTextResult.docs ?? []) {
  const docId = String(item.doc?.id);
  const score = item.score?.toFixed(2);
  const keyword = String(item.doc?.keyword);
  const text = String(item.doc?.text ?? "").slice(0, 60);
  console.log(`${docId.padEnd(5)} | ${score} | ${keyword.padEnd(15)} | ${text}...`);
}
```

```go Go theme={null}
fullTextResult, err := coll.Query(ctx, lambdadb.QueryInput{
  Size: lambdadb.Int64(10),
  Query: map[string]interface{}{
    "bool": []interface{}{
      map[string]interface{}{"queryString": map[string]interface{}{"query": "I hate managing servers", "defaultField": "text"}, "occur": "must"},
      map[string]interface{}{"queryString": map[string]interface{}{"query": "keyword:serverless"}, "occur": "filter"},
    },
  },
  ConsistentRead: lambdadb.Bool(true),
})
if err != nil { log.Fatal(err) }
log.Println("🔍 Search Results:")
for _, r := range fullTextResult.Docs {
  doc := r.Doc
  docID := fmt.Sprintf("%v", doc["id"])
  score := "n/a"
  if r.Score != nil { score = fmt.Sprintf("%.2f", *r.Score) }
  keyword := fmt.Sprintf("%v", doc["keyword"])
  text := fmt.Sprintf("%v", doc["text"])
  if len(text) > 60 { text = text[:60] }
  log.Printf("%-5s | %-5s | %-15s | %s...", docID, score, keyword, text)
}
```

After the writes are visible, `doc1` and `doc3` satisfy the keyword filter and contain matching text terms. `doc2` is excluded by the filter. Inspect the scores returned by your request; their exact values and ordering are not fixed by this example.

To show counts for values in the `keyword` field alongside these results, add [keyword facets](https://docs.lambdadb.ai/guides/search/facets.md). Counts cover all matching documents, including the query's filters. They support this lexical query, but cannot be added to the hybrid query in Step 6.

## 🔍 Step 6: Hybrid search

Now let's combine full-text search with [vector similarity](https://docs.lambdadb.ai/guides/search/vector.md) in a [hybrid query](https://docs.lambdadb.ai/guides/search/hybrid.md). This example uses L2 normalization to combine the two retrieval paths:

```python Python theme={null}
with LambdaDB(project_api_key="your_api_key_here", base_url="YOUR_BASE_URL", project_name="YOUR_PROJECT_NAME") as client:
    coll = client.collection(collection_name)
    res = coll.query(
        size=10,
        query={
            "l2": [
                {"queryString": {"query": "I hate managing servers", "defaultField": "text"}},
                {"knn": {"field": "vector", "k": 5, "queryVector": [(i + 1) / 64 for i in range(64)]}},
            ]
        },
        consistent_read=True,
    )
    print("🔄 Hybrid Search Results:")
    for item in res.docs:
        score = f"{item.score:.2f}" if item.score is not None else "n/a"
        print(f"{item.doc.get('id')} | {score} | {item.doc.get('text', '')[:50]}...")
```

```typescript TypeScript theme={null}
const hybridResult = await collection.query({
  size: 10,
  query: {
    l2: [
      { queryString: { query: "I hate managing servers", defaultField: "text" } },
      { knn: { field: "vector", k: 5, queryVector: Array.from({ length: 64 }, (_, i) => (i + 1) / 64) } },
    ],
  },
  consistentRead: true,
});
console.log("🔄 Hybrid Search Results:");
for (const item of hybridResult.docs ?? []) {
  console.log(`${item.doc?.id} | ${item.score?.toFixed(2)} | ${String(item.doc?.text).slice(0, 50)}...`);
}
```

```go Go theme={null}
hybridResult, err := coll.Query(ctx, lambdadb.QueryInput{
  Size: lambdadb.Int64(10),
  Query: map[string]interface{}{
    "l2": []interface{}{
      map[string]interface{}{"queryString": map[string]interface{}{"query": "I hate managing servers", "defaultField": "text"}},
      map[string]interface{}{"knn": map[string]interface{}{"field": "vector", "k": 5, "queryVector": demoVector(1)}},
    },
  },
  ConsistentRead: lambdadb.Bool(true),
})
if err != nil { log.Fatal(err) }
log.Println("🔄 Hybrid Search Results:")
for _, r := range hybridResult.Docs {
  doc := r.Doc
  docID := fmt.Sprintf("%v", doc["id"])
  score := "n/a"
  if r.Score != nil { score = fmt.Sprintf("%.2f", *r.Score) }
  keyword := fmt.Sprintf("%v", doc["keyword"])
  text := fmt.Sprintf("%v", doc["text"])
  if len(text) > 50 { text = text[:50] }
  log.Printf("%s | %s | %s | %s...", docID, score, keyword, text)
}
```

The result items have the same shape as the full-text results. This query has no keyword filter, so `doc2` can also appear. The sample vectors only demonstrate the request format; they are not embeddings of the document text and do not demonstrate semantic relevance. Exact scores and ordering depend on the data and query.

**Hybrid fusion options:**

* `rrf` (Reciprocal Rank Fusion): Combines result ranks from different search methods
* `l2` (L2 Normalization): Normalizes scores using L2 norm
* `mm` (Min-Max Normalization): Simple linear scaling to 0-1 range
* `bayesian` (Bayesian Fusion): Automatically calibrates each retrieval path's scores on retained candidates before combining them

### Try Bayesian hybrid search

To try Bayesian fusion with the same documents, replace `l2` with `bayesian` in the examples above and add a candidate budget alongside `size` in the query call:

* **Python:** `candidate_size=30`
* **TypeScript:** `candidateSize: 30`
* **Go:** `CandidateSize: lambdadb.Int64(30)`

Without reranking, this budget is required and must satisfy `1 <= size <= candidateSize` within the [candidate limit](https://docs.lambdadb.ai/guides/get-started/limits.md#search-and-reads). It controls retrieval and score calibration depth for each path; `knn.k` remains independent. Changing the budget can change scores and ranking.

Keep exactly two unboosted subqueries and use `bayesian` only at the top level of `query`. The fused scores are heuristic scores, not relevance probabilities. For complete requests, constraints, and optional reranking, see [Bayesian hybrid query](https://docs.lambdadb.ai/guides/search/hybrid.md#bayesian-hybrid-query).

### Rerank the results

For a model to evaluate the retrieved documents against your question, add query-level [native reranking](https://docs.lambdadb.ai/guides/search/native-reranking.md), using `text` as the stored field to evaluate. It works with the full-text and hybrid queries above, including caller-provided vectors. LambdaDB manages provider credentials, and reranking consumes [inference usage](https://docs.lambdadb.ai/guides/costs/understanding-costs.md#inference-usage).

When reranking is applied, `score` is the model's evaluation and `retrievalScore` preserves the original retrieval or fusion score. Check `rerank.status` before interpreting results. For Bayesian queries with reranking, move the candidate budget into `rerank.candidateSize` and omit top-level `candidateSize`; see [candidate counts](https://docs.lambdadb.ai/guides/search/native-reranking.md#candidate-counts).

## 🧹 Step 7: Clean up

When you're finished experimenting, [delete the collection](https://docs.lambdadb.ai/guides/collections/manage-collections.md#delete-a-collection) to remove the sample documents and indexes:

```python Python theme={null}
with LambdaDB(project_api_key="your_api_key_here", base_url="YOUR_BASE_URL", project_name="YOUR_PROJECT_NAME") as client:
    client.collections.delete(collection_name=collection_name)
```

```typescript TypeScript theme={null}
await client.collection(collectionName).delete();
```

```go Go theme={null}
_, err = client.Collection(collectionName).Delete(ctx)
if err != nil { log.Fatal(err) }
```

## 🚀 Next steps

* **CLI**: Import JSONL and search from your terminal with the [LambdaDB CLI](https://docs.lambdadb.ai/guides/get-started/use-with-cli.md)

* **MCP**: Connect an AI assistant using [Use the MCP server](https://docs.lambdadb.ai/guides/get-started/use-with-mcp.md)

* **Advanced Queries**: Explore complex patterns in our [Query Guide](https://docs.lambdadb.ai/guides/search/search-overview.md)

* **Bulk Operations**: Learn about large-scale data ingestion in our [Bulk Operations Guide](https://docs.lambdadb.ai/guides/documents/bulk-upsert-data.md)

* **API Reference**: Comprehensive documentation at our [API Reference](https://docs.lambdadb.ai/reference/api/introduction.md)

## 🤝 Support

Need help? Visit our [Community Slack](https://join.slack.com/t/lambdadbcommunity/shared_invite/zt-3sg7565zm-sCTW3odRkEQt~auWUVVsTw) for support and discussions.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.