Конфигурация и эксплуатацияConfiguration and operations

Настройки API-хоста, логи, структура хранилища и типовые проблемы (версия 9.0.47).

API host settings, logs, storage layout and common issues (version 9.0.47).

Где лежат файлыWhere files live

Путь (пакет deb/rpm)Path (deb/rpm package)ЧтоWhat
/opt/bsa-search-apiПриложениеApplication
/etc/bsa-search-api/appsettings.jsonАдрес и портAddress and port
/etc/bsa-search-api/searchServiceManager.jsonНастройки индексовIndex settings
/etc/bsa-search-api/NLog.configЛогированиеLogging
/var/BsaSearch/searchindexДанные индексовIndex data
/var/log/BsaSearch/Bsa.Search.Api.HostЛогиLogs

В zip-сборке все файлы конфигурации лежат рядом с исполняемыми файлами.

In the zip build all config files sit next to the binaries.

Порт: appsettings.jsonPort: appsettings.json

appsettings.json
{
  "Bsa.Search.Api": {
    "Host": "http://+:2664"
  }
}

Секция Cluster в том же файле включает кластерный режим — см. Кластерный режим.

The Cluster section of the same file turns on cluster mode — see Cluster mode.

Индексы: searchServiceManager.jsonIndexes: searchServiceManager.json

searchServiceManager.json
{
  "ClearMemoryInterval": "00:01:00",
  "CloseIndexInterval": "00:30:00",
  "IndexLiveInterval": 60,
  "NeverCloseIndex": "false",
  "PercentMemoryUsage": 80,
  "ShardCount": 16,
  "AvailablePhysicalMemory": 32000,
  "IndexFolder": "/var/BsaSearch/searchindex",
  "IndexFormat": "Segment",
  "SegmentPositionFields": ""
}
ПараметрParameterВ поставкеShippedЕсли не заданIf omittedОписаниеDescription
IndexFormatSegmentSegmentФормат новых индексов: Segment — сегментный (старые индексы конвертируются при запуске), Legacy — старый формат без конвертации.Format of new indexes: Segment — segment (old indexes are converted at startup), Legacy — previous format, no conversion.
SegmentPositionFields""""Поля с позициями слов для фраз и ~n (через запятую или массив).Fields with word positions for phrases and ~n (comma-separated or an array).
ShardCount160Число шард нового индекса: 16 и больше — 16 шард, иначе один. В формате Legacy: 0 — DiskDocumentIndex, 1–15 — ShardDocumentIndex с одним шардом, 16 — 16 шард.Shards of a new index: 16 or more — 16 shards, otherwise one. In Legacy format: 0 — DiskDocumentIndex, 1–15 — ShardDocumentIndex with one shard, 16 — 16 shards.
IndexFolder/var/BsaSearch/searchindexкаталог приложенияapp folderКаталог с индексами.Folder with indexes.
AvailablePhysicalMemory3200032768Объём RAM в МБ, от которого считается процент использования. Выставьте под сервер.RAM in MB used as the base for usage percent. Set it for your server.
PercentMemoryUsage8080При превышении порога запускается очистка памяти и закрытие индексов.Above this threshold memory cleanup starts and indexes get closed.
ClearMemoryInterval00:01:0000:05:00Как часто проверять память и чистить кэши.How often memory is checked and caches cleared.
CloseIndexInterval00:30:0001:30:00Как часто искать неиспользуемые индексы.How often unused indexes are looked for.
IndexLiveInterval6020Минут без обращений, после которых индекс закрывается.Minutes without access after which an index is closed.
NeverCloseIndexfalsefalsetrue — никогда не закрывать индексы по времени и памяти.true — never close indexes by time or memory.

NeedCloseIndex и UseLocalTermRepository из старых версий больше не используются — удалите их из конфигурации.

NeedCloseIndex and UseLocalTermRepository from older versions are no longer used — remove them from the config.

Логирование: NLog.configLogging: NLog.config

По умолчанию: консоль (Info), файл всех событий (Info) и файл ошибок (Error). Чтобы снизить нагрузку на диск, поднимите уровень до Warn.

Default: console (Info), all-events file (Info) and errors file (Error). To reduce disk load, raise the level to Warn.

NLog.config
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <targets>
    <target xsi:type="ColoredConsole" name="ColoredConsole-Trace"
            layout="${longdate} ${uppercase:${level}} ${logger} ${message}"
            useDefaultRowHighlightingRules="true" />
    <target xsi:type="File" name="FlatFile-Trace"
            layout="${longdate} ${uppercase:${level}} ${logger} ${message}"
            fileName="/Logs/Bsa.Search.Api.Host/${shortdate}-Trace.log"
            keepFileOpen="false" encoding="UTF-8" />
    <target xsi:type="File" name="FlatFile-Error"
            layout="${longdate} ${uppercase:${level}} ${logger} ${message} ${exception:format=tostring}"
            fileName="/Logs/Bsa.Search.Api.Host/${shortdate}-Errors.log"
            keepFileOpen="false" encoding="UTF-8" />
  </targets>
  <rules>
    <logger name="*" minlevel="Info" writeTo="ColoredConsole-Trace" />
    <logger name="*" minlevel="Info" writeTo="FlatFile-Trace" />
    <logger name="*" minlevel="Error" writeTo="FlatFile-Error" />
  </rules>
</nlog>

Формат индексов и конвертацияIndex format and conversion

По умолчанию новые индексы создаются в сегментном формате, а индексы старого формата конвертируются при запуске сервиса: копия в {имя}.segment-tmp, затем старая папка становится {имя}.legacy-bak. Запуск задерживается на время конвертации; нужна резервная копия и место на диске под оба индекса. Сегментный индекс не хранит текст полей — если нужны подсветка или фильтрующие поля, укажите "IndexFormat": "Legacy".

By default new indexes use the segment format and old-format indexes are converted at service startup: a copy goes to {name}.segment-tmp, then the old folder becomes {name}.legacy-bak. Startup is delayed for the conversion; you need a backup and disk room for both indexes. The segment index does not store field texts — if you need highlights or filter fields, set "IndexFormat": "Legacy".

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

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

Структура хранилища индекса (формат Legacy)Index storage layout (Legacy format)

ФайлыFilesСодержимоеContents
Meta.info, Meta.sinfoМетаданные индекса; Meta.info — маркер папки индекса.Index metadata; Meta.info marks an index folder.
Temp/Журнал записи (WAL) до сброса в шарды.Write-ahead journal before flushing to shards.
Filters/Фильтрующие поля.Filter fields.
0/ … F/Данные шардов (у DiskDocumentIndex — один шард 0/).Shard data (DiskDocumentIndex has a single shard 0/).
ShortDocuments*Проиндексированные документы (термы и поля).Indexed documents (terms and fields).
Terms*, terms.ninfoПостинги термов и словарь термов шарда.Term postings and the shard term dictionary.
Deleted*Удалённые и заменённые документы.Deleted and replaced documents.
ExternalIds*, *.hidx, *.htailВнешние идентификаторы и хеш-индекс для поиска по ним.External ids and their hash index.
*.browИндекс строк: позиция и размер каждой записи.Row index: position and size of every record.
*.back, *.reindexРезервная копия и маркер на время переиндексации.Backup and marker during reindexing.

Индексы старого формата DiskDocumentIndex (файлы ShortDocuments.idb в корне папки) конвертируются автоматически при первом открытии; пока идёт конвертация, индекс не готов (isReady = false).

Old-format DiskDocumentIndex indexes (ShortDocuments.idb in the folder root) are converted automatically on first open; while converting, the index is not ready (isReady = false).

Обслуживание через APIMaintenance via API

МетодMethodНазначениеPurpose
GET /api/v1/search/infoСостояние всех индексов (в т.ч. идёт ли переиндексация)State of all indexes (incl. running reindex)
GET /api/v1/search/flush?index=Сбросить журнал и буферы на дискFlush journal and buffers to disk
GET /api/v1/search/close?index=Закрыть индекс и освободить памятьClose the index and free memory
GET /api/v1/search/reindex?index=Переиндексировать (схлопнуть дубли записей)Reindex (collapse duplicate records)
GET /api/v1/search/clearОчистить кэши всех индексовClear caches of all indexes

Типовые проблемыCommon issues

Нехватка памятиRunning out of memory

Чаще всего из-за коротких масок (а*) на большом индексе. Проверьте AvailablePhysicalMemory — он должен соответствовать реальному объёму RAM. Слишком низкий порог замедлит поиск: индексы будут часто выгружаться.

Usually caused by short masks (a*) on a large index. Check that AvailablePhysicalMemory matches the real RAM. Too low a threshold slows search: indexes get unloaded too often.

Долгий запуск после обновленияSlow start after an upgrade

Идёт конвертация старых индексов в сегментный формат — дождитесь записи в логе о числе документов и времени. Если конвертация индекса упала, он остаётся в старом формате.

Old indexes are being converted to the segment format — wait for the log entry with the document count and time. If an index fails to convert, it stays in the old format.

Нет подсветки и полей в ответеNo highlights or fields in the response

Так работает сегментный индекс: он не хранит текст. Нужен текст — храните его в своей БД или используйте "IndexFormat": "Legacy" (откат описан на странице сегментного индекса).

That is how the segment index works: it stores no text. Need the text — keep it in your DB or use "IndexFormat": "Legacy" (rollback is described on the segment index page).

Нехватка места на дискеRunning out of disk space

Файлы *.back можно удалить, если не идёт переиндексация (проверьте GET /api/v1/search/info).

*.back files can be deleted if no reindex is running (check GET /api/v1/search/info).

Остановка службыStopping the service

При остановке индекс сбрасывает журнал на диск; на больших индексах это может занять до нескольких минут — не убивайте процесс принудительно.

On stop the index flushes its journal to disk; on large indexes this can take minutes — do not kill the process.

Нетекстовые данныеNon-text data

Слова длиннее 100 символов режутся на куски, но гигантские «слова» (base64, бинарные данные) всё равно раздувают словарь. Фильтруйте их до индексации.

Words over 100 characters are split, but huge “words” (base64, binary data) still bloat the dictionary. Filter them out before indexing.