Repository navigation
11. Sleopok Engine
ZeroLevel.Sleopok.Engine is an embeddable inverted-index search engine — a simplified, in-process alternative to Elasticsearch/Lucene for the cases where a local, file-based full-text index is enough. It builds on top of PartitionStorage for durability and TextAnalizer for tokenization.
- Ships as a separate NuGet:
ZeroLevel.Sleopok.Engine. - Target framework:
netstandard2.1. Transitively depends onZeroLevelof the matching version.
- Embedded. Runs in-process. The index is a folder on disk you control.
-
Attribute-driven. Mark fields with
[SleoIndex]— no DSL, no schema files. -
Relevance out of the box. Per-field
Boost, position-aware scoring, optional exact-match. -
Collections supported.
string[],List<string>, anyIEnumerable<string>— indexed element-by-element. -
Streaming read-back.
GetAll()streams every(field, token, documents)triple without materializing the index in memory. - Deduplicated, compressed posting lists. GZip merge, duplicate doc-ids collapsed.
dotnet add package ZeroLevel.Sleopok.Engineusing ZeroLevel.Sleopok.Engine.Models;
public sealed class Book
{
public string Id { get; set; }
[SleoIndex("title", boost: 10.0f, avaliableForExactMatch: true)]
public string Title { get; set; }
[SleoIndex("author", boost: 5.0f, avaliableForExactMatch: true)]
public string Author { get; set; }
[SleoIndex("tags", boost: 2.0f)]
public string[] Tags { get; set; }
}Id is whatever identifies a document; the extractor Func<T, string> is given to the engine.
using ZeroLevel.Sleopok.Engine;
var engine = new SleoEngine<Book>("./index", b => b.Id);
using (var builder = engine.CreateBuilder())
{
await builder.Write(new[]
{
new Book { Id = "01", Title = "War and Peace", Author = "Tolstoy", Tags = new[] { "classic", "novel" } },
new Book { Id = "02", Title = "Crime and Punishment", Author = "Dostoevsky", Tags = new[] { "classic" } },
new Book { Id = "03", Title = "Hyperion", Author = "Dan Simmons", Tags = new[] { "sci-fi", "novel" } },
});
await builder.Complete(); // flushes, merges, dedups posting lists
}Call Write multiple times within one builder session — everything merges on Complete.
var reader = engine.CreateReader();
// ranked fuzzy match — any subset of tokens, higher overlap + proximity wins
var ranked = await reader.Search(new[] { "war", "peace" }, exactMatch: false);
foreach (var pair in ranked)
Console.WriteLine($"[{pair.Key}] score={pair.Value:F2}");
// strict — only docs that contain *all* tokens in at least one exact-match-eligible field
var exact = await reader.Search(new[] { "war", "peace" }, exactMatch: true);await foreach (var field in reader.GetAll())
{
Console.WriteLine($"field: {field.Field}");
await foreach (var entry in field.Records)
Console.WriteLine($" {entry.Token} → [{string.Join(",", entry.Documents)}]");
}GetAll() yields tokens as they are read from disk — no whole-field materialization.
-
Tokenization. Per indexed field:
TextAnalizer.ExtractWords+ToLowerInvariant(). -
Partitioning. Tokens are bucketed by
StringHash.DotNetFullHash(token) % 47— one partition file per bucket per field. -
Posting lists.
(token → [doc_id, ...])deduplicated onComplete()and GZip-compressed viaCompressor. -
Scoring.
PositionDocScorecombines (a) fraction of query tokens matched, (b) proximity of their positions, (c) per-fieldBoost. Exact-match bypasses (b) and simply checks presence of every token in one eligible field.
[SleoIndex(name, boost = 1.0f, avaliableForExactMatch = false)]| Parameter | Meaning |
|---|---|
name |
Storage field name. Defaults to the member name if blank. |
boost |
Per-field score multiplier at query time. |
avaliableForExactMatch |
If false, the field is skipped when Search(..., exactMatch: true) is invoked. |
Works on:
- Public properties.
- Public fields.
- Fields whose declared type is
string, an array,List<T>, or anyIEnumerableother thanstring(strings never count as collections).
| Type | Purpose |
|---|---|
SleoEngine<T>(string indexFolder, Func<T, string> identityExtractor) |
Entry point. Owns the folder. |
SleoEngine<T>.HasData() |
true if any partition file exists. |
SleoEngine<T>.CreateBuilder() : IIndexBuilder<T> |
Batch writer (Write, Complete, Dispose). |
SleoEngine<T>.CreateReader() : IIndexReader<T> |
Search(string[] tokens, bool exactMatch), GetAll(). |
FieldRecords(string Field, IAsyncEnumerable<TokenDocuments> Records) |
One streamed field. |
TokenDocuments(string Token, string[] Documents) |
One (token → docs) entry. |
DataStorage |
Lower-level public API — raw writes, IterateAllDocuments, HasData. |
Compressor.Compress(string[]) / DecompressToDocuments(byte[]) |
Posting-list codec. |
Does it support deletes / updates? Not directly — the index is append-only within a build session. Rebuild to reflect deletions. Duplicate writes of the same (token, doc_id) collapse on merge.
Are writes thread-safe? Do not call IIndexBuilder<T>.Write concurrently on the same builder. The underlying PartitionStorage is ThreadSafeWriting = true, but the token-level processing is not.
Case sensitivity? Queries and indexed text are normalized via ToLowerInvariant() — "Hello" matches "HELLO" and "hello".
Stop-words / stemming? Not built in. Pre-process yourself (e.g. Iveonik.Stemmers) and feed cleaned tokens into an additional [SleoIndex] field.
Collection field as one token or tokenized? Each element is fed through the same tokenizer as a single value — so Tags = new[] { "sci-fi", "novel" } produces three tokens: sci, fi, novel.
How big can an index get? Limited by disk space and token count per file (partition storage buckets tokens by hash % 47 — tune the constant by forking if you need more). A single posting list is bounded by Compressor and the 32 MB frame limit of ZeroLevel serialization.
-
Layer fields.
title(raw),title_stem(stemmed, lower boost),title_ngram(3-grams, lowest boost) → handles typos and morphology. -
Pre-filter with a Bloom filter. If you index hundreds of millions of docs, put a
BloomFilterin front ofSearchto avoid round-trips for obviously missing tokens. -
Exact-match eligibility. Keep
avaliableForExactMatch = trueonly for fields where equality is meaningful (title, author ID). A stemmed field shouldn't participate. -
Rebuild vs. append. There is no delete; re-index when your source truth changes non-trivially. For incremental updates of independent documents, multiple
Write+ oneCompleteis fine.
Application basics
Data & serialization
Networking
Text & search