Сегментный индекс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 thewal_{n}.logjournal 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 formula | BM25 |
| Подсветка, поля документа, фильтрующие поля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
{
"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 |
|---|---|
IndexFormat | Segment — сегментный формат (по умолчанию: ключа нет, пустое или неизвестное значение); 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. |
ShardCount | 16 и больше — новый индекс получает 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:
- Старый индекс загружается, журнал сбрасывается, документы копируются в
{имя}.segment-tmp.The old index is loaded, its journal flushed, documents copied into{name}.segment-tmp. - После успешного копирования старая папка переименовывается в
{имя}.legacy-bak, новая получает имя индекса.After a successful copy the old folder is renamed to{name}.legacy-bakand the new one takes the index name. - В лог пишутся число документов и время.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
- Остановите сервис.Stop the service.
- Удалите или переименуйте папку
{имя}, переименуйте{имя}.legacy-bakобратно в{имя}.Delete or rename the{name}folder, rename{name}.legacy-bakback to{name}. - Укажите
"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— нижняя граница.SettotalHitsLimitfor 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 andtotalHitsis 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должна совпадать с датой, по которой сортирует ваша БД, иначе порядок страниц разойдётся.Publishedmust 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.
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:
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”. |
FlushDocumentCount | 20000 | Сбросить буфер в сегмент после стольких документов.Flush the buffer into a segment after this many documents. |
FlushTokenCount | 5000000 | …или после стольких слов (память буфера).…or after this many words (buffer memory). |
FlushInterval | 00:00:30 | …или по времени.…or by time. |
SyncWrites | true | fsync журнала при каждой записи; false быстрее, но при сбое ОС можно потерять последние записи.fsync the journal on every write; false is faster but an OS crash may lose the last writes. |
MergeEnabled | true | Фоновое слияние сегментов.Background segment merging. |
MergeFactor | 10 | Сколько сегментов сливается за раз.How many segments are merged at once. |
MaxMergedDocuments | 5000000 | Предел размера сегмента, полученного слиянием.Size limit of a merged segment. |
Bm25K1, Bm25B | 1.2, 0.75 | Параметры BM25.BM25 parameters. |
Файлы на дискеFiles on disk
{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.