Сегментный индексSegment index

SegmentDocumentIndex (один индекс) и SegmentShardDocumentIndex (1 или 16 шардов, замена ShardDocumentIndex) — формат хранения по умолчанию начиная с Bsa.Search.Core 10.0.50 и API-хоста 9.0.47.

SegmentDocumentIndex (single index) and SegmentShardDocumentIndex (1 or 16 shards, replaces ShardDocumentIndex) — the default storage format since Bsa.Search.Core 10.0.50 and API host 9.0.47.

  • Устройство как в Lucene и SQLite FTS5: неизменяемые сегменты, сжатые списки вхождений, чтение через memory-mapped файлы, фоновое слияние сегментов.Built like Lucene and SQLite FTS5: immutable segments, compressed postings, memory-mapped reads, background segment merging.
  • Документ пишется в журнал wal_{n}.log и буфер в памяти — и сразу находится поиском. Буфер сбрасывается в сегмент по числу документов, слов или раз в 30 секунд; после сбоя журнал повторяется.A document goes to the wal_{n}.log journal and an in-memory buffer — and is searchable at once. The buffer is written to a segment by document count, word count or every 30 seconds; after a crash the journal is replayed.
  • Документ попадает в шард по хэшу внешнего id; число шард задаётся при создании и потом не меняется (только пересозданием индекса). Словарь термов у шард общий.A document goes to a shard by the hash of its external id; the shard count is set at creation and never changes (only by recreating the index). Shards share one term dictionary.
  • Reindex() сливает все сегменты в один и физически удаляет удалённые документы.Reindex() merges all segments into one and physically removes deleted documents.

Чем отличается от старого форматаCompared with the previous format

Старый форматPrevious formatСегментныйSegment
ХранениеStorageдокументы с текстом полей + инвертированный индексdocuments with field texts + inverted indexтолько инвертированный индекс, даты и внешние idinverted index, dates and external ids only
ИндексацияIndexingчерез временные файлы и шардыvia temp files and shardsжурнал + буфер в памяти, без хранения текстаjournal + in-memory buffer, no text stored
Сортировка по датеDate sortingполный переборfull scanранний выход по диапазонам датearly exit by date ranges
Подсчёт найденныхHit countвсегда точныйalways exactточный или до предела (TotalHitsLimit)exact or up to a limit (TotalHitsLimit)
РелевантностьRelevanceсвоя формулаown formulaBM25
Подсветка, поля документа, фильтрующие поляHighlights, document fields, filter fieldsестьyesнетno

Индекс не хранит текст полей. Поиск возвращает внешний id, внутренний id, Published, Timestamp и Score. Не поддерживаются: подсветка (ShowHighlight) и получение полей документа, фильтрующие поля и Filter в запросе, Export/CopyTo/Import/AddFilter, Find* и GetIndex. Храните текст в своей БД, а Bsa.Search используйте для поиска id; если нужны подсветка или фильтрующие поля — оставьте старый формат (IndexFormat = Legacy). Полей — не больше 64.

The index does not store field texts. Search returns the external id, internal id, Published, Timestamp and Score. Not supported: highlights (ShowHighlight) and document fields, filter fields and Filter in a request, Export/CopyTo/Import/AddFilter, Find* and GetIndex. Keep the text in your own DB and use Bsa.Search to find ids; if you need highlights or filter fields, keep the previous format (IndexFormat = Legacy). At most 64 fields.

Настройка сервиса: searchServiceManager.jsonService settings: searchServiceManager.json

searchServiceManager.json
{
  "IndexFolder": "/var/BsaSearch/searchindex",
  "ShardCount": 16,
  "IndexFormat": "Segment",
  "SegmentPositionFields": "subject,body",
  "CloseIndexInterval": "00:30:00",
  "IndexLiveInterval": 60,
  "NeverCloseIndex": "false",
  "PercentMemoryUsage": 80,
  "AvailablePhysicalMemory": 32000
}
ПараметрParameterЗначениеValue
IndexFormatSegment — сегментный формат (по умолчанию: ключа нет, пустое или неизвестное значение); Legacy — старый формат без конвертации.Segment — segment format (default: no key, empty or unknown value); Legacy — previous format, no conversion.
SegmentPositionFieldsПоля с позициями слов (фразы, ~n): строка через запятую или массив ["subject","body"]. По умолчанию пусто. Позиции увеличивают индекс — указывайте только поля, где нужны фразы.Fields with word positions (phrases, ~n): a comma-separated string or an array ["subject","body"]. Empty by default. Positions grow the index — list only fields that need phrases.
ShardCount16 и больше — новый индекс получает 16 шард, иначе один. У существующего индекса число шард записано в Segment.sinfo и не меняется.16 or more — a new index gets 16 shards, otherwise one. An existing index keeps the count stored in Segment.sinfo.
CloseIndexInterval, IndexLiveInterval, NeverCloseIndexЗакрытие неиспользуемых индексов; сегментный индекс снова открывается при следующем обращении.Closing unused indexes; a segment index reopens on the next access.

Существующий индекс открывается в своём формате (по папке: есть Segment.sinfo — сегментный); новые индексы создаются в настроенном формате. С Legacy уже сконвертированные индексы продолжают открываться как сегментные.

An existing index opens in its own format (by folder: Segment.sinfo means segment); new indexes are created in the configured format. With Legacy, already converted indexes still open as segment ones.

Конвертация старых индексовConverting old indexes

При IndexFormat = Segment (или если ключ не задан) сервис при запуске сам конвертирует индексы старого формата (ShardDocumentIndex, DiskDocumentIndex):

With IndexFormat = Segment (or no key) the service converts old-format indexes (ShardDocumentIndex, DiskDocumentIndex) at startup:

  1. Старый индекс загружается, журнал сбрасывается, документы копируются в {имя}.segment-tmp.The old index is loaded, its journal flushed, documents copied into {name}.segment-tmp.
  2. После успешного копирования старая папка переименовывается в {имя}.legacy-bak, новая получает имя индекса.After a successful copy the old folder is renamed to {name}.legacy-bak and the new one takes the index name.
  3. В лог пишутся число документов и время.The document count and time go to the log.

Запуск задерживается на время конвертации (примерно время чтения всех документов старого индекса) — планируйте окно обслуживания. Перед обновлением сделайте резервную копию папки индексов; на диске нужно место под старый и новый индекс одновременно. {имя}.legacy-bak — единственное место, где остаётся текст документов: удаляйте вручную после проверки.

Startup is delayed for the conversion (about the time to read every document of the old index) — plan a maintenance window. Back up the index folder before upgrading; the disk needs room for the old and new index at once. {name}.legacy-bak is the only place that still holds document texts: delete it manually after checking.

  • Прерванная во время копирования конвертация начинается заново; прерванная после копирования — при следующем запуске только завершаются переименования.A conversion interrupted while copying starts over; one interrupted after copying only finishes the renames on the next start.
  • Если конвертация индекса завершилась ошибкой, он остаётся в старом формате и открывается как раньше; ошибка — в логе.If an index fails to convert, it stays in the old format and opens as before; the error is in the log.

ОткатRollback

  1. Остановите сервис.Stop the service.
  2. Удалите или переименуйте папку {имя}, переименуйте {имя}.legacy-bak обратно в {имя}.Delete or rename the {name} folder, rename {name}.legacy-bak back to {name}.
  3. Укажите "IndexFormat": "Legacy" и запустите сервис. Документы, добавленные после конвертации, в старом индексе отсутствуют.Set "IndexFormat": "Legacy" and start the service. Documents added after the conversion are missing from the old index.

Поиск: рекомендации по скоростиSearch: speed tips

  • Задавайте totalHitsLimit для частых слов: точный подсчёт сотен тысяч совпадений — основная стоимость такого запроса; с пределом запрос заканчивается после набора страницы, totalHits — нижняя граница.Set totalHitsLimit for frequent words: counting hundreds of thousands of matches exactly is the main cost of such a query; with a limit it ends once the page is full and totalHits is a lower bound.
  • Сортируйте по дате в Bsa.Search (orderField = PUBLISHED) и запрашивайте только страницу (50–200): индекс идёт от самых новых документов и останавливается, когда страница набрана.Sort by date in Bsa.Search (orderField = PUBLISHED) and fetch one page (50–200): the index walks from the newest documents and stops when the page is full.
  • Не выгружайте тысячи id для фильтрации в БД: индексируйте атрибуты (папка, владелец, флаги) как поля документа и добавляйте их в запрос (folder:inbox).Do not pull thousands of ids to filter in your DB: index attributes (folder, owner, flags) as document fields and add them to the query (folder:inbox).
  • Дата Published должна совпадать с датой, по которой сортирует ваша БД, иначе порядок страниц разойдётся.Published must match the date your DB sorts by, otherwise page order will differ.

Использование из кодаUsing it from code

SearchServiceManager выбирает формат так же, как сервис: если объект настроек реализует IIndexFormatSettings, берутся его IndexFormat и SegmentPositionFields; иначе — Segment без полей с позициями и конвертация старых индексов при создании менеджера.

SearchServiceManager picks the format like the service: if the settings object implements IIndexFormatSettings, its IndexFormat and SegmentPositionFields are used; otherwise — Segment without position fields, and old indexes are converted when the manager is created.

C#
public sealed class MySettings : ISearchServiceManagerSettings, IIndexFormatSettings
{
    // ... ISearchServiceManagerSettings members
    public IndexFormat IndexFormat => IndexFormat.Segment; // or IndexFormat.Legacy
    public IReadOnlyList<string> SegmentPositionFields => new[] { "subject", "body" };
}

Индекс можно создать и напрямую:

The index can also be created directly:

C#
var wordSelector = new IndexWordSelector();
var morphology = new DefaultMorphology(new WordDictionary(), wordSelector);
var settings = new SegmentIndexSettings
{
    // word positions (phrases, ~n, /n) are stored only for these fields
    PositionFields = new List<string> { "subject", "body" },
};

// 16 shards and a shared term dictionary in D:\indexes\mail
var index = new SegmentShardDocumentIndex(
    new ShardSettings(@"D:\indexes", "mail", ShardSize.Sixteen),
    morphology,
    wordSelector, // null - IndexWordSelector
    settings);
var searchService = new SearchServiceEngine(index);

var doc = new IndexDocument("mail-1", 0, DateTime.UtcNow, DateTime.UtcNow);
doc.Add("subject".GetField("quarterly report"));
doc.Add("body".GetField("the report is attached"));
doc.Add("folder".GetField("inbox"));
searchService.Index(new[] { doc }); // searchable at once, before the flush

var result = searchService.Search(new SearchQueryRequest
{
    Query = "report & folder:inbox".Parse("*"),
    Field = "*",
    Size = 50,
    IsShort = true,
    OrderField = SortOrderFields.Published,
    Order = SortOrder.Desc,
    TotalHitsLimit = 10_000, // count matches up to 10 000 (like track_total_hits)
});

// without shards:
// new SegmentDocumentIndex(folder, morphology, termRepository: null, wordSelector, settings)

Настройки: SegmentIndexSettingsSettings: SegmentIndexSettings

СвойствоPropertyПо умолчаниюDefaultОписаниеDescription
PositionFields—Поля, для которых хранятся позиции слов. Фразы и расстояния точны только в этих полях; в остальных фраза находится как «все слова в документе».Fields that keep word positions. Phrases and proximity are exact only in these fields; elsewhere a phrase matches as “all words in the document”.
FlushDocumentCount20000Сбросить буфер в сегмент после стольких документов.Flush the buffer into a segment after this many documents.
FlushTokenCount5000000…или после стольких слов (память буфера).…or after this many words (buffer memory).
FlushInterval00:00:30…или по времени.…or by time.
SyncWritestruefsync журнала при каждой записи; false быстрее, но при сбое ОС можно потерять последние записи.fsync the journal on every write; false is faster but an OS crash may lose the last writes.
MergeEnabledtrueФоновое слияние сегментов.Background segment merging.
MergeFactor10Сколько сегментов сливается за раз.How many segments are merged at once.
MaxMergedDocuments5000000Предел размера сегмента, полученного слиянием.Size limit of a merged segment.
Bm25K1, Bm25B1.2, 0.75Параметры BM25.BM25 parameters.

Файлы на дискеFiles on disk

text
{IndexFolder}/{name}/
  Segment.sinfo      shard count and routing (do not edit)
  terms/             shared term dictionary
  0/ ... 15/         shards: segments 000000NN.*, segments_N, wal_*.log
Файлы сегментаSegment filesСодержимоеContents
segments_NКоммит: список действующих сегментов и полей.Commit: the list of live segments and fields.
wal_{n}.logЖурнал предзаписи (кадры с CRC-32).Write-ahead log (frames with CRC-32).
*.metaМетаданные сегмента (пишутся последними).Segment metadata (written last).
*.tdi, *.tixСловарь термов сегмента и его разреженный индекс.Segment term dictionary and its sparse index.
*.doc, *.posСписки вхождений с таблицами пропуска; позиции слов.Postings with skip tables; word positions.
*.colДаты публикации и индексации, длина, смещение внешнего id (32 байта на документ).Published and index dates, length, external id offset (32 bytes per document).
*.ext, *.exhВнешние идентификаторы и их хэш-индекс.External ids and their hash index.
{id}_{gen}.delБитовая маска удалённых документов.Bitmap of deleted documents.

Сравнение индексовIndex comparison

ИндексIndexХранениеStorageДля чегоUse caseЭкспортExport
MemoryDocumentIndexОперативная памятьRAMТесты, небольшие и временные наборыTests, small and temporary setsпотокstream
DiskDocumentIndexДиск, 1 шардDisk, 1 shardНебольшие и средние индексыSmall and medium indexesпотокstream
ShardDocumentIndexДиск, 1 или 16 шардовDisk, 1 or 16 shardsБольшие индексы, высокая нагрузкаLarge indexes, heavy loadв другой индексinto another index
FileDocumentIndexИндекс по файлуIndex over a fileЛоги и большие текстовые файлыLogs and large text files—
SegmentShardDocumentIndexДиск, сегменты, 1 или 16 шардов; по умолчанию в API-хостеDisk, segments, 1 or 16 shards; API host defaultБольшие индексы без хранения текста, BM25, сортировка по датеLarge indexes without stored text, BM25, date sorting—
SegmentDocumentIndexДиск, неизменяемые сегментыDisk, immutable segmentsТо же без шардThe same without shards—

Memory, Disk и ShardDocumentIndex хранят текст полей (подсветка, поля документа, фильтрующие поля); сегментные индексы — нет.

Memory, Disk and ShardDocumentIndex store field texts (highlights, document fields, filter fields); segment indexes do not.