On this page
What Vespa.NET is
Vespa.NET is an open-source, strongly-typed .NET SDK for Vespa.ai, released under the MIT licence and targeting .NET 8 LTS and .NET 10. Outmatic maintains it and is an official Vespa.ai implementation partner. It brings document models, schema generation, document operations and search into a C# application. Without an SDK, a .NET application hand-rolls JSON payloads, YQL strings and schema management. Vespa.NET connects these responsibilities through model attributes and typed builders, while retaining access to Vespa query parameters and application-package configuration. The examples below follow the repository quick start, using one product model throughout.
Install and run Vespa locally
Start a local Vespa 8 container with Docker running, then create a console application and install the client. Port 8080 serves documents and queries; port 19071 serves configuration and deployment.
docker run --detach --name vespa --publish 8080:8080 --publish 19071:19071 vespaengine/vespa:8
dotnet new console --name VespaQuickstart --framework net10.0
cd VespaQuickstart
dotnet add package Vespa.NETUse --framework net8.0 for .NET 8. Wait for http://localhost:19071/ApplicationStatus to respond before deploying. The package is on NuGet; the GitHub repository contains the source, samples and documentation.
Define a document model in C#
Add this model as Product.cs. The document attribute declares the schema name and namespace; the ID attribute keeps the identifier out of the JSON fields. Field names also drive serialization, so the query builder can resolve the same mapping.
using Vespa.Models.Attributes;
using Vespa.Models.Schema;
using Vespa.Models.Tensors;
[VespaDocument("product", Namespace = "myapp")]
[VespaRankProfile("semantic", Inherits = "default", FirstPhase = "closeness(field, embedding)")]
[VespaRankProfile("hybrid", Inherits = "default",
FirstPhase = "closeness(field, embedding) + nativeRank(product_name)")]
public record Product
{
[VespaId]
public string Id { get; init; } = "";
[VespaField(Name = "product_name", IndexingMode = IndexingMode.IndexAttributeSummary)]
public string Name { get; init; } = "";
[VespaField(Name = "price", IndexingMode = IndexingMode.AttributeSummary)]
public decimal Price { get; init; }
[VespaField(Name = "category", IndexingMode = IndexingMode.IndexAttributeSummary)]
public string Category { get; init; } = "";
[VespaTensor("tensor<float>(x[4])", EnableIndex = true, DistanceMetric = DistanceMetric.Euclidean)]
public VespaTensor Embedding { get; init; } = null!;
}The tensor declaration specifies four float cells and an indexed vector field. These tiny vectors make the example self-contained. In an application, match the tensor dimension and distance metric to your embedding model. The two rank profiles are generated with the schema.
Deploy the schema
Start Program.cs with the client configuration below. DeploySchemaAsync<Product>() generates the Vespa .sd schema and deploys an application package containing the schema and service configuration to the self-hosted config server. Wait for application readiness after activation before feeding.
using Vespa;
using Vespa.Documents;
using Vespa.Models;
using Vespa.Models.Tensors;
using Vespa.Search;
var options = new VespaClientOptions
{
Endpoint = "http://localhost:8080",
ConfigServerEndpoint = "http://localhost:19071",
DefaultNamespace = "myapp"
};
using var client = new VespaClient(options);
// Deploy schema from C# attributes
await client.Admin.DeploySchemaAsync<Product>();
// Allow the application container to become ready after activation
using var startup = new CancellationTokenSource(TimeSpan.FromMinutes(2));
while (!await client.IsReadyAsync(startup.Token))
await Task.Delay(TimeSpan.FromMilliseconds(500), startup.Token);To inspect the generated schema, use the schema builder. Put its using directive at the top of the file:
using Vespa.Models.Schema;
var schema = VespaSchemaBuilder.GenerateSchema<Product>();
Console.WriteLine(schema);Schema deployment changes the application on that instance, so use a separate development instance for this walkthrough. If an application is already deployed, configure its endpoint and skip deployment. The schema guide covers inspecting the generated schema, multi-type packages and custom services.xml. Vespa Cloud deployment uses its CLI or CI pipeline.
Feed documents
Continue in Program.cs by creating a product and issuing a single put. The typed document extensions infer the schema and namespace from the model attributes.
var product = new Product
{
Id = "p-1",
Name = "Laptop",
Price = 999.99m,
Category = "electronics",
Embedding = VespaTensor.FromDenseValues<float>([0.1f, 0.2f, 0.3f, 0.4f])
};
await client.Documents.PutAsync(product.Id, product);The document/v1 surface also covers updates and corpus operations. Choose an operation according to what must change:
| Operation | Use |
|---|---|
| Conditional puts | Apply a write only when a selection condition holds. An unmet condition produces HTTP 412 and VespaConditionNotMetException. |
| Partial updates | Assign fields or apply numeric operations with a typed lambda builder, without replacing the whole document. |
| Tensor modify / add / remove | Modify cells, add cells to mapped or mixed tensors, or remove cells and blocks by address. |
| Selection-based update / delete | Apply a selection expression across documents. The high-level operations automatically follow continuation tokens. |
| Document visiting | Enumerate documents with automatic continuation; use page APIs and persist tokens after processing for resumable exports. |
| Bulk feed | Mix puts, updates and deletes with bounded concurrency and backpressure, preserving source order per document. |
// Field-level update with typed lambda builder
await client.Documents.UpdateFieldsAsync<Product>(product.Id, ops => ops
.Field(p => p.Name, FieldOp.Assign("New Name"))
.Field(p => p.Price, FieldOp.Multiply(0.9)));await client.Documents.PutAsync(product.Id, product,
condition: "product.price > 0"); // HTTP 412 → VespaConditionNotMetException
// Conditional put with create (Vespa ≥ 8.178): apply even when the document
// does not exist yet.
await client.Documents.PutAsync(product.Id, product,
condition: "product.price > 0", create: true);// Visit
await foreach (var d in client.Documents.VisitAsync<Product>(selection: "product.price > 100"))
Console.WriteLine(d.Fields?.Name);For a mixed feed, add the feed namespace and submit operations together. Check the returned counts and errors:
using Vespa.Feed;
// Mixed operations with per-document ordering
FeedOperation[] operations =
[
FeedOperation.Put("p-1", product),
FeedOperation.Update<Product>("p-1", update => update.Field(p => p.Price, FieldOp.Assign(49.99m))),
FeedOperation.Delete<Product>("p-2")
];
var mixed = await client.Feed.FeedAsync(operations, new FeedOptions { MaxConcurrency = 32 });
Console.WriteLine($"{mixed.SuccessCount}/{mixed.TotalOperations} operations succeeded");
foreach (var error in mixed.Errors)
Console.WriteLine($"{error.OperationIndex}: {error.DocumentId} — {error.Message}");A successful write response and visibility in search have different guarantees. Use direct document retrieval when checking a specific write. See the document operations reference for conditions, tensor operations and manual continuation.
Query with YQL
The YQL builder resolves fields from C# expressions and produces a search request. Add the shown using directive at the top of Program.cs. This hybrid example supplies both a query vector and text, then selects the model’s hybrid rank profile.
using Vespa.Query;
var queryEmbedding = VespaTensor.FromDenseValues<float>([0.1f, 0.2f, 0.3f, 0.5f]);
var request = YqlBuilder<Product>
.Select()
.Where(w => w.HybridSearch(p => p.Embedding, "query_embedding", "text", totalTargetHits: 100))
.Limit(20)
.ToSearchRequest()
.WithRankProfile("hybrid")
.WithQueryTensor("query_embedding", queryEmbedding)
.WithUserInput("text", "laptop");
var results = await client.Search.SearchAsync<Product>(request);HybridSearch retrieves nearest-neighbor candidates and supplies text matches for ranking through Vespa’s rank() operator. It does not union two independent candidate sets. The profile combines vector closeness with nativeRank(product_name). Evaluate relevance on representative queries before choosing candidate counts or a ranking formula; the SDK does not choose those for your data.
The same builder handles field filters, projection and ordering:
using Vespa.Query;
var yql = YqlBuilder<Product>
.Select(p => p.Name, p => p.Price)
.Where(w =>
{
w.Field(p => p.Price).GreaterThan(10);
w.Field(p => p.Name).Contains("laptop");
})
.OrderBy(p => p.Price, descending: true)
.Limit(20)
.Build();Dependency injection and resilience
For ASP.NET Core, register the SDK with AddVespaClient. It integrates with IHttpClientFactory and uses Microsoft.Extensions.Http.Resilience for HTTP retry and circuit breaking. Your service consumes IVespaClient.
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Vespa;
using Vespa.Documents;
using Vespa.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddVespaClient(new VespaClientOptions
{
Endpoint = "http://localhost:8080",
DefaultNamespace = "myapp",
EnableRetry = true
});
// Named client (multi-cluster)
builder.Services.AddVespaClient("analytics", new VespaClientOptions
{
Endpoint = "http://analytics-vespa:8080"
});
// Inject
public class ProductService(IVespaClient vespa)
{
public Task<VespaDocument<Product>?> GetAsync(string id)
=> vespa.Documents.GetAsync<Product>(id);
}Named registrations support multiple clusters, such as a separate analytics deployment. Re-registering the same name replaces its Vespa configuration; other names remain independent. HTTP resilience options are enforced through DI registration. A directly constructed client supports feed-level retry, while the options-only constructor also configures its HTTP handler and owns its lifetime. Keep those lifetimes in mind when moving a console prototype into a hosted application.
Observability
VespaActivitySource and VespaClientMetrics publish through the .NET ActivitySource and Meter primitives. The SDK adds no OpenTelemetry dependency. In an application that already configures OpenTelemetry, register its source and meter with your existing pipeline:
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;
builder.Services.AddOpenTelemetry()
.WithTracing(b => b.AddSource("Vespa.NET"))
.WithMetrics(m => m.AddMeter("Vespa.NET"));Traces cover search, document operations and feed pipelines. Metrics include request counts, request duration, errors and documents written. Query text and document IDs are excluded from trace tags by default. ASP.NET Core health-check registration adds VespaHealthCheck, which calls the client readiness check:
builder.Services.AddHealthChecks().AddVespa();Integration testing
Install the optional Vespa.NET.Testcontainers package and run Docker for integration tests. The helper starts a real instance, exposes mapped endpoints and creates a client for it:
using Vespa.Testcontainers;
await using var vespa = new VespaContainer();
await vespa.StartAsync();
var client = vespa.CreateClient("test");
await client.Admin.DeploySchemaAsync<Product>();VespaContainer defaults to vespaengine/vespa:8, pinned to the major version. It owns the client returned by CreateClient and disposes it with the container. After schema activation, wait for application readiness as in the console example before writing or searching. Testcontainers startup waits for the config server; deploying a schema and serving application traffic are separate stages.
Packages
Choose packages by responsibility. The main client already brings in the models package transitively; the container helper is an optional test dependency.
| Package | Contents |
|---|---|
| Vespa.NET | Client, dependency injection, document and feed APIs, YQL and schema builders. |
| Vespa.NET.Models | DTOs, model attributes and tensor types without client dependencies. |
| Vespa.NET.Testcontainers | Docker-backed Vespa fixtures for integration tests. |
All three target .NET 8 and .NET 10 under the MIT licence. Browse the SDK source and documentation on GitHub or install the client from NuGet.
When you need more than the SDK
Outmatic is an official Vespa.ai implementation partner. We work on schema design, relevance tuning, data pipelines and migration from Elasticsearch or OpenSearch. Production handover includes the code and architecture documentation your team needs to operate and extend the application. Contact our Vespa engineers to discuss the work around your SDK integration.
