POST/v2/namespaces/:namespace/query

Query, filter, full-text search and vector search documents.

A query retrieves documents in a single namespace, returning the ordered or highest-ranked documents that match the query’s filters. turbopuffer supports the following types of queries:

turbopuffer is fast by default. See Performance for how you can influence performance. This concept ports the examples below; the full query reference is on turbopuffer.com.

Examples

The query vector must have the same dimensionality as the vector column being queried.

# choose best region: https://turbopuffer.com/docs/regions
curl https://gcp-us-east4.turbopuffer.com/v2/namespaces/query-vector-example-curl/query \
  -X POST --fail-with-body \
  -H "Authorization: Bearer $TURBOPUFFER_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
   "rank_by": [
     "vector",
     "ANN",
     [0.1, 0.1]
   ],
   "limit": 10
 }'

# Response payload
# {
#   "rows": [
#     { "$dist": 0.0, "id": 1 },
#     { "$dist": 2.0, "id": 2 },
#     ...
#   ]
# }
// dotnet add package Turbopuffer
using System;
using System.Collections.Generic;
using Turbopuffer;
using Turbopuffer.Models.Namespaces;

using var tpuf = new TurbopufferClient
{
    // API tokens are created in the dashboard: https://turbopuffer.com/dashboard
    // Loaded from TURBOPUFFER_API_KEY env var by default. Override if necessary:
    // ApiKey = "...",

    // Pick the right region: https://turbopuffer.com/docs/regions
    Region = "gcp-us-east4",
};

var ns = tpuf.Namespace("query-vector-example-csharp");

var result = await ns.Query(
    new NamespaceQueryParams
    {
        RankBy = RankBy.Ann("vector", new[] { 0.1f, 0.1f }),
        Limit = 10,
    }
);
foreach (var row in result.GetRows())
{
    Console.WriteLine(row);
}
// Prints a list of row-oriented documents:
// {"$dist": 0.0, "id": 1}
// {"$dist": 2.0, "id": 2}
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/turbopuffer/turbopuffer-go/v2"
	"github.com/turbopuffer/turbopuffer-go/v2/option"
)

func main() {
	ctx := context.Background()
	tpuf := turbopuffer.NewClient(
		// API tokens are created in the dashboard: https://turbopuffer.com/dashboard
		option.WithAPIKey(os.Getenv("TURBOPUFFER_API_KEY")),
		option.WithRegion("gcp-us-east4"), // choose best region: https://turbopuffer.com/docs/regions
	)

	ns := tpuf.Namespace("query-vector-example-go")
	// If an error occurs, this call raises an error if a retry was not successful.
	result, err := ns.Query(
		ctx,
		turbopuffer.NamespaceQueryParams{
			RankBy: turbopuffer.NewRankByAnn("vector", []float32{0.1, 0.1}),
			Limit: turbopuffer.LimitParam{
				Total: 10,
			},
		},
	)
	if err != nil {
		panic(err)
	}
	fmt.Print(turbopuffer.PrettyPrint(result.Rows))

	// Returns a row-oriented result:
	// [
	//   {"id": 1, "vector": null, "$dist": 0.0},
	//   {"id": 2, "vector": null, "$dist": 2.0}
	// ]
}
package com.turbopuffer.docs;

import com.turbopuffer.client.okhttp.*;
import com.turbopuffer.models.namespaces.*;
import java.util.*;

public class QueryVector {

  public static void main(String[] args) {
    var tpuf = TurbopufferOkHttpClient.builder()
      .fromEnv()
      // API tokens are created in the dashboard: https://turbopuffer.com/dashboard
      .apiKey(System.getenv("TURBOPUFFER_API_KEY"))
      .region("gcp-us-east4") // choose best region: https://turbopuffer.com/docs/regions
      .build();

    var ns = tpuf.namespace("query-vector-example-java");

    var result = ns.query(
      NamespaceQueryParams.builder()
        .rankBy(RankBy.ann("vector", List.of(0.1f, 0.1f)))
        .limit(10)
        .build()
    );
    System.out.println(result.rows().get());
    // Prints a list of row-oriented documents:
    // [
    //   {id=1, vector=None, $dist=0.0},
    //   {id=2, vector=None, $dist=2.0}
    // ]
  }
}
# $ pip install turbopuffer
import turbopuffer
import os

tpuf = turbopuffer.Turbopuffer(
    # API tokens are created in the dashboard: https://turbopuffer.com/dashboard
    api_key=os.getenv("TURBOPUFFER_API_KEY"),
    region="gcp-us-east4", # choose best region: https://turbopuffer.com/docs/regions
)

ns = tpuf.namespace(f'query-vector-example-py')

# If an error occurs, this call raises a turbopuffer.APIError if a retry was not successful.
result = ns.query(
    rank_by=("vector", "ANN", [0.1, 0.1]),
    limit=10
)
print(result.rows)

# Prints a list of row-oriented documents:
# [
#   Row(id=1, vector=None, $dist=0.0),
#   Row(id=2, vector=None, $dist=2.0)
# ]
# $ gem install turbopuffer
require "turbopuffer"

tpuf = Turbopuffer::Client.new(
  # API tokens are created in the dashboard: https://turbopuffer.com/dashboard
  api_key: ENV["TURBOPUFFER_API_KEY"],
  region: "gcp-us-east4", # choose best region: https://turbopuffer.com/docs/regions
)

ns = tpuf.namespace("query-vector-example-rb")

# If an error occurs, this call raises a Turbopuffer::Errors::APIError if a retry was not successful.
result = ns.query(
  rank_by: [
    "vector",
    "ANN",
    [0.1, 0.1],
  ],
  limit: 10,
)
puts result.rows

# Prints a list of row-oriented documents:
# {id: 1, dist: 0.0}
# {id: 2, dist: 2.0}
// $ cargo add turbopuffer tokio --features tokio/full
use turbopuffer::Client;
use turbopuffer::serde_json;
use turbopuffer::types::RankBy;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // The API key is read from TURBOPUFFER_API_KEY. Create one here: https://turbopuffer.com/dashboard
    let client = Client::builder()
        .region("gcp-us-east4") // choose best region: https://turbopuffer.com/docs/regions
        .build()?;

    let ns = client.namespace("query-vector-example-rs");

    // If an error occurs, this call returns a turbopuffer::Error once retries are exhausted.
    let result = ns
        .query()
        .rank_by(RankBy::ann("vector", [0.1, 0.1]))
        .limit(10)
        .send()
        .await?;
    println!("{}", serde_json::to_string_pretty(&result.rows)?);

    // Prints the row-oriented results:
    // [
    //   {"id": 1, "$dist": 0.0},
    //   {"id": 2, "$dist": 2.0}
    // ]

    Ok(())
}
// $ npm install @turbopuffer/turbopuffer
import { Turbopuffer } from "@turbopuffer/turbopuffer";

const tpuf = new Turbopuffer({
  // API tokens are created in the dashboard: https://turbopuffer.com/dashboard
  apiKey: process.env.TURBOPUFFER_API_KEY,
  region: "gcp-us-east4", // choose best region: https://turbopuffer.com/docs/regions
});

const ns = tpuf.namespace(`query-vector-example-ts`);

const result = await ns.query({
  rank_by: [
    "vector",
    "ANN",
    [0.1, 0.1],
  ],
  limit: 10,
});
console.log(result.rows);

Filters

When you need to filter documents, you can combine filters with vector search or use them alone. Here’s an example of finding recent public documents:

# choose best region: https://turbopuffer.com/docs/regions
curl https://gcp-us-east4.turbopuffer.com/v2/namespaces/query-filters-example-curl/query \
  -X POST --fail-with-body \
  -H "Authorization: Bearer $TURBOPUFFER_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
   "filters": [
     "And",
     [
       ["timestamp", "Gte", "2024-03-01T00:00:00.000Z"],
       ["public", "Eq", true]
     ]
   ],
   "rank_by": [
     "vector",
     "ANN",
     [0.1, 0.2, 0.3]
   ],
   "limit": 10,
   "include_attributes": ["title", "timestamp"]
 }'
// dotnet add package Turbopuffer
using System;
using System.Collections.Generic;
using Turbopuffer;
using Turbopuffer.Models.Namespaces;

using var tpuf = new TurbopufferClient
{
    // Pick the right region: https://turbopuffer.com/docs/regions
    Region = "gcp-us-east4",
};

var ns = tpuf.Namespace("query-filters-example-csharp");

var result = await ns.Query(
    new NamespaceQueryParams
    {
        Filters = Filter.And(
            Filter.Gte("timestamp", new DateTime(2024, 3, 1, 0, 0, 0, DateTimeKind.Utc)), // Documents after March 1, 2024
            Filter.Eq("public", true)
        ),
        RankBy = RankBy.Ann("vector", new[] { 0.1f, 0.2f, 0.3f }), // Optional: include vector to combine with filters
        Limit = 10,
        IncludeAttributes = new List<string> { "title", "timestamp" },
    }
);

foreach (var row in result.GetRows())
{
    Console.WriteLine(row);
}
// Prints a list of row-oriented documents:
// {"$dist": 0.15, "id": 1, "timestamp": "2024-03-02T00:00:00.000000000Z", "title": "Getting Started Guide"}
// {"$dist": 0.28, "id": 2, "timestamp": "2024-03-03T00:00:00.000000000Z", "title": "Advanced Features"}
package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"github.com/turbopuffer/turbopuffer-go/v2"
	"github.com/turbopuffer/turbopuffer-go/v2/option"
)

func main() {
	ctx := context.Background()
	tpuf := turbopuffer.NewClient(
		option.WithRegion("gcp-us-east4"), // choose best region: https://turbopuffer.com/docs/regions
	)

	ns := tpuf.Namespace("query-filters-example-go")

	result, err := ns.Query(
		ctx,
		turbopuffer.NamespaceQueryParams{
			Filters: turbopuffer.NewFilterAnd([]turbopuffer.Filter{
				// Documents after March 1, 2024
				turbopuffer.NewFilterGte("timestamp", time.Date(2024, 3, 1, 0, 0, 0, 0, time.UTC)),
				turbopuffer.NewFilterEq("public", true),
			}),
			// Optional: include vector to combine with filters
			RankBy: turbopuffer.NewRankByAnn("vector", []float32{0.1, 0.2, 0.3}),
			Limit: turbopuffer.LimitParam{
				Total: 10,
			},
			IncludeAttributes: turbopuffer.IncludeAttributesParam{
				StringArray: []string{"title", "timestamp"},
			},
		},
	)
	if err != nil {
		panic(err)
	}
	fmt.Print(turbopuffer.PrettyPrint(result.Rows))

	// Returns a row-oriented result:
	// [
	//   {"id": 1, "$dist": 0.15, "title": "Getting Started Guide", "timestamp": "2024-03-02T00:00:000000000Z"},
	//   {"id": 2, "$dist": 0.28, "title": "Advanced Features", "timestamp": "2024-03-03T00:00:000000000Z"}
	// ]
}
package com.turbopuffer.docs;

import com.turbopuffer.client.okhttp.*;
import com.turbopuffer.models.namespaces.*;
import java.time.*;
import java.util.*;

public class QueryFilters {

  public static void main(String[] args) {
    var tpuf = TurbopufferOkHttpClient.builder()
      .fromEnv()
      .region("gcp-us-east4") // choose best region: https://turbopuffer.com/docs/regions
      .build();

    var ns = tpuf.namespace("query-filters-example-java");

    var result = ns.query(
      NamespaceQueryParams.builder()
        .filters(
          Filter.and(
            Filter.gte("timestamp", ZonedDateTime.of(2024, 3, 1, 0, 0, 0, 0, ZoneOffset.UTC)), // Documents after March 1, 2024
            Filter.eq("public", true)
          )
        )
        .rankBy(RankBy.ann("vector", List.of(0.1f, 0.2f, 0.3f))) // Optional: include vector to combine with filters
        .limit(10)
        .includeAttributes("title", "timestamp")
        .build()
    );

    System.out.println(result.rows().get());
    // Prints a list of row-oriented documents:
    // [
    //   {id=1, vector=None, $dist=0.15, title='Getting Started Guide', timestamp='2024-03-02T00:00:00'},
    //   {id=2, vector=None, $dist=0.28, title='Advanced Features', timestamp='2024-03-03T00:00:00'}
    // ]
  }
}
from datetime import datetime
import turbopuffer

tpuf = turbopuffer.Turbopuffer(
    region='gcp-us-east4', # choose best region: https://turbopuffer.com/docs/regions
)

ns = tpuf.namespace(f'query-filters-example-py')

result = ns.query(
    filters=('And', (
        ('timestamp', 'Gte', datetime(2024, 3, 1, 0, 0, 0)),  # Documents after March 1, 2024
        ('public', 'Eq', True)
    )),
    rank_by=("vector", "ANN", [0.1, 0.2, 0.3]),  # Optional: include vector to combine with filters
    limit=10,
    include_attributes=['title', 'timestamp']
)
print(result.rows)

# Prints a list of row-oriented documents:
# [
#   Row(id=1, vector=None, $dist=0.15, title='Getting Started Guide', timestamp='2024-03-02T00:00:000000000Z'),
#   Row(id=2, vector=None, $dist=0.28, title='Advanced Features', timestamp='2024-03-03T00:00:000000000Z'),
# ]
require "turbopuffer"

tpuf = Turbopuffer::Client.new(
  region: "gcp-us-east4", # choose best region: https://turbopuffer.com/docs/regions
)

ns = tpuf.namespace("query-filters-example-rb")

result = ns.query(
  filters: [
    "And",
    [
      ["timestamp", "Gte", DateTime.new(2024, 3, 1, 0, 0, 0)], # Documents after March 1, 2024
      ["public", "Eq", true],
    ],
  ],
  rank_by: [
    "vector",
    "ANN",
    [0.1, 0.2, 0.3],
  ], # Optional: include vector to combine with filters
  limit: 10,
  include_attributes: ["title", "timestamp"],
)
puts result.rows

# Prints a list of row-oriented documents:
# {id: 1, dist: 0.15, title: "Getting Started Guide", timestamp: '2024-03-02T00:00:000000000Z'}
# {id: 2, dist: 0.28, title: "Advanced Features", timestamp: '2024-03-03T00:00:000000000Z'}
use turbopuffer::Client;
use turbopuffer::jiff::Timestamp;
use turbopuffer::serde_json;
use turbopuffer::types::{Filter, RankBy};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // The API key is read from TURBOPUFFER_API_KEY. Create one here: https://turbopuffer.com/dashboard
    let client = Client::builder()
        .region("gcp-us-east4") // choose best region: https://turbopuffer.com/docs/regions
        .build()?;

    let ns = client.namespace("query-filters-example-rs");

    let result = ns
        .query()
        .filters(Filter::and([
            // Documents after March 1, 2024
            Filter::gte("timestamp", "2024-03-01T00:00:00Z".parse::<Timestamp>()?),
            Filter::eq("public", true),
        ]))
        // Optional: include vector to combine with filters
        .rank_by(RankBy::ann("vector", [0.1, 0.2, 0.3]))
        .limit(10)
        .include_attributes(["title", "timestamp"])
        .send()
        .await?;
    println!("{}", serde_json::to_string_pretty(&result.rows)?);

    // Prints the row-oriented results:
    // [
    //   {"id": 1, "$dist": 0.15, "timestamp": "2024-03-02T00:00:00.000000000Z", "title": "Getting Started Guide"},
    //   {"id": 2, "$dist": 0.28, "timestamp": "2024-03-03T00:00:00.000000000Z", "title": "Advanced Features"}
    // ]

    Ok(())
}
import { Turbopuffer } from "@turbopuffer/turbopuffer";

const tpuf = new Turbopuffer({
  region: "gcp-us-east4", // choose best region: https://turbopuffer.com/docs/regions
});

const ns = tpuf.namespace(`query-filters-example-ts`);

const result = await ns.query({
  filters: [
    "And",
    [
      ["timestamp", "Gte", new Date("2024-03-01")], // Documents after March 1, 2024
      ["public", "Eq", true],
    ],
  ],
  rank_by: [
    "vector",
    "ANN",
    [0.1, 0.2, 0.3],
  ], // Optional: include vector to combine with filters
  limit: 10,
  include_attributes: ["title", "timestamp"],
});

console.log(result.rows);
// Returns a row-oriented result:
// [
//   {id: 1, $dist: 0.15, title: "Getting Started Guide", timestamp: "2024-03-02T00:00:000000000Z"},
//   {id: 2, $dist: 0.28, title: "Advanced Features", timestamp: "2024-03-03T00:00:000000000Z"}
// ]