Create predicate index
Index one or more metadata fields so predicate queries run faster.
Every operation works on both Vector DB stores (you supply raw vectors) and AI stores (you supply text or images and Ahnlich AI generates the embeddings for you). Use the Vector DB / AI switch in the sample below.
Parameters
| Parameter | Type | Description |
|---|---|---|
store | string | Store to index. |
predicates | list | Metadata fields to index. |
schema | string · optional | Schema to target. Defaults to public. |
All requests accept an optional
schemafield. When omitted, the server uses thepublicschema.
Behavior
- Speeds up Get by predicate and predicate filters used in similarity search.
- Indexing existing fields is safe — it builds over data already stored.
Sample query
- Database engine
- AI proxy
- Python
- Node.js
- Go
- Rust
- CLI
Python
import asyncio
from grpclib.client import Channel
from ahnlich_client_py.grpc.services.db_service import DbServiceStub
from ahnlich_client_py.grpc.db import query as db_query
async def create_predicate_index():
async with Channel(host="127.0.0.1", port=1369) as channel:
client = DbServiceStub(channel)
response = await client.create_pred_index(
db_query.CreatePredIndex(
store="my_store",
schema="analytics",
predicates=["label", "category"]
)
)
# response.created_indexes shows how many indexes were created
print(response)
if __name__ =="__main__":
asyncio.run(create_predicate_index())
TypeScript
import { createDbClient } from "ahnlich-client-node";
import { CreatePredIndex } from "ahnlich-client-node/grpc/db/query_pb";
async function createPredicateIndex() {
const client = createDbClient("127.0.0.1:1369");
await client.createPredIndex(
new CreatePredIndex({
store: "my_store",
schema: "analytics",
predicates: ["label", "category"],
})
);
console.log("Predicate indices created successfully");
}
createPredicateIndex();
Go
package main
import (
"context"
"fmt"
"log"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
dbsvc "github.com/deven96/ahnlich/sdk/ahnlich-client-go/grpc/services/db_service"
dbquery "github.com/deven96/ahnlich/sdk/ahnlich-client-go/grpc/db/query"
)
const ServerAddr = "127.0.0.1:1369"
func stringPtr(value string) *string { return &value }
type ExampleDBClient struct {
conn *grpc.ClientConn
client dbsvc.DBServiceClient
ctx context.Context
}
func NewDBClient(ctx context.Context) (*ExampleDBClient, error) {
conn, err := grpc.NewClient(ServerAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return nil, fmt.Errorf("failed to dial DB server %q: %w", ServerAddr, err)
}
client := dbsvc.NewDBServiceClient(conn)
return &ExampleDBClient{conn: conn, client: client, ctx: ctx}, nil
}
func (c *ExampleDBClient) Close() error {
return c.conn.Close()
}
// -------------------- Create Predicate Index --------------------
func (c *ExampleDBClient) exampleCreatePredicateIndex() error {
_, err := c.client.CreatePredIndex(c.ctx, &dbquery.CreatePredIndex{
Store: "my_store",
Schema: stringPtr("analytics"), // Optional: defaults to public when omitted
Predicates: []string{"label"},
})
if err != nil {
return err
}
fmt.Println("Predicate index created for store: my_store")
return nil
}
// -------------------- Main --------------------
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := NewDBClient(ctx)
if err != nil {
log.Fatalf("Failed to create DB client: %v", err)
}
defer client.Close()
if err := client.exampleCreatePredicateIndex(); err != nil {
log.Fatalf("CreatePredicateIndex failed: %v", err)
}
}
Rust
use ahnlich_client_rs::db::DbClient;
use ahnlich_types::db::query::CreatePredIndex;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// connect to DB server
let db_client = DbClient::new("127.0.0.1:1369".to_string()).await?;
let tracing_id: Option<String> = None;
// Create predicate index request
let params = CreatePredIndex {
store: "my_store".to_string(),
schema: Some("analytics".to_string()),
predicates: vec!["label".to_string()], // metadata field names to index
};
// Call the client
match db_client.create_pred_index(params, tracing_id).await {
Ok(result) => {
println!("Created predicate index: {:?}", result);
}
Err(err) => {
eprintln!("Error creating predicate index: {:?}", err);
}
}
Ok(())
}
CREATEPREDINDEX (author, category) IN my_store- Python
- Node.js
- Go
- Rust
- CLI
Python
import asyncio
from grpclib.client import Channel
from ahnlich_client_py.grpc.services.ai_service import AiServiceStub
from ahnlich_client_py.grpc.ai import query as ai_query
async def create_predicate_index():
async with Channel(host="127.0.0.1", port=1370) as channel:
client = AiServiceStub(channel)
response = await client.create_pred_index(
ai_query.CreatePredIndex(
store="my_store",
schema="analytics",
predicates=["job", "rank"]
)
)
print(response) # CreateIndex(created_indexes=1)
if __name__ == "__main__":
asyncio.run(create_predicate_index())
TypeScript
import { createAiClient } from "ahnlich-client-node";
import { CreatePredIndex } from "ahnlich-client-node/grpc/ai/query_pb";
async function createPredicateIndex() {
const client = createAiClient("127.0.0.1:1370");
await client.createPredIndex(
new CreatePredIndex({
store: "ai_store",
schema: "analytics",
predicates: ["brand", "category"],
})
);
console.log("Predicate indices created");
}
createPredicateIndex();
Go
package main
import (
"context"
"fmt"
"log"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
aiquery "github.com/deven96/ahnlich/sdk/ahnlich-client-go/grpc/ai/query"
aisvc "github.com/deven96/ahnlich/sdk/ahnlich-client-go/grpc/services/ai_service"
)
const AIAddr = "127.0.0.1:1370"
func stringPtr(value string) *string { return &value }
type ExampleAIClient struct {
conn *grpc.ClientConn
client aisvc.AIServiceClient
ctx context.Context
}
func NewAIClient(ctx context.Context) (*ExampleAIClient, error) {
conn, err := grpc.DialContext(ctx, AIAddr, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock())
if err != nil {
return nil, fmt.Errorf("failed to dial AI server %q: %w", AIAddr, err)
}
client := aisvc.NewAIServiceClient(conn)
return &ExampleAIClient{conn: conn, client: client, ctx: ctx}, nil
}
func (c *ExampleAIClient) Close() error {
return c.conn.Close()
}
// ---- CreatePredIndex ----
func (c *ExampleAIClient) exampleCreatePredIndexAI() error {
_, err := c.client.CreatePredIndex(c.ctx, &aiquery.CreatePredIndex{
Store: "ai_store",
Schema: stringPtr("analytics"), // Optional: defaults to public when omitted
Predicates: []string{"f"},
})
if err != nil {
return err
}
fmt.Println(`Predicate index created successfully with logic: Predicates: []string{"f"},`)
return nil
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
client, err := NewAIClient(ctx)
if err != nil {
log.Fatalf(" Failed to create AI client: %v", err)
}
defer client.Close()
if err := client.exampleCreatePredIndexAI(); err != nil {
log.Fatalf(" CreatePredIndex failed: %v", err)
}
}
Rust
use ahnlich_client_rs::ai::AiClient;
use ahnlich_client_rs::error::AhnlichError;
use ahnlich_types::ai::query::CreatePredIndex;
use ahnlich_types::ai::server::CreateIndex;
#[tokio::main]
async fn main() -> Result<(), AhnlichError> {
// Connect to the AI service
let ai_client = AiClient::new("http://127.0.0.1:1370".to_string())
.await
.expect("Failed to connect AI client");
// Define which store and which predicates to index
let params = CreatePredIndex {
store: "Deven Kicks".to_string(),
schema: Some("analytics".to_string()),
predicates: vec!["Brand".to_string(), "Vintage".to_string()],
};
// Call the API
let response: CreateIndex = ai_client.create_pred_index(params, None).await?;
println!(" Created predicate indexes: {:?}", response);
Ok(())
}
CREATEPREDINDEX (label, category) IN my_storeResponse
The number of indexes successfully created.