Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

API リファレンス

Index

Laurus 検索エンジンをラップするメインクラスです。

new \Laurus\Index(?string $path = null, ?Schema $schema = null)

コンストラクタ

パラメータデフォルト説明
$pathstring|nullnull永続ストレージのディレクトリパス。null の場合はインメモリインデックスを作成します。
$schemaSchema|nullnullスキーマ定義。省略時は空のスキーマが使用されます。

メソッド

メソッド説明
putDocument(string $id, array $doc): voidドキュメントをアップサート(upsert)します。同じ ID の既存バージョンをすべて置換します。
addDocument(string $id, array $doc): void既存バージョンを削除せずにドキュメントチャンクを追記します。
getDocuments(string $id): array指定 ID の全保存バージョンを返します。
deleteDocuments(string $id): void指定 ID の全バージョンを削除します。
commit(): voidバッファリングされた書き込みをフラッシュし、すべての保留中の変更を検索可能にします。
search(mixed $query, int $limit = 10, int $offset = 0): array検索クエリを実行します。SearchResult の配列を返します。
stats(): arrayインデックス統計("documentCount""vectorFields")を返します。

search の query 引数

$query パラメータは以下のいずれかを受け付けます:

  • DSL 文字列(例: "title:hello""embedding:\"memory safety\"")
  • Lexical クエリオブジェクトTermQueryPhraseQueryBooleanQuery など)
  • Vector クエリオブジェクトVectorQueryVectorTextQuery
  • SearchRequest(完全な制御が必要な場合)

Schema

Index のフィールドとインデックスタイプを定義します。

new \Laurus\Schema()

フィールドメソッド

メソッド説明
addTextField(string $name, bool $stored = true, bool $indexed = true, bool $termVectors = false, ?string $analyzer = null): void全文フィールド(転置インデックス、BM25)。$analyzer にはパラメータ不要の組込名("standard" / "english" / "keyword" / "simple" / "noop"、または addAnalyzer で登録したカスタム名)を指定します。Lindera 辞書パスが必要な Japanese プリセットは、lindera tokenizer を含むカスタム analyzer として登録し、名前で参照してください。
addIntegerField(string $name, bool $stored = true, bool $indexed = true, bool $multiValued = false): void64 ビット整数フィールド。$multiValued = true で整数配列を受け付け(範囲クエリは “any match”)。
addFloatField(string $name, bool $stored = true, bool $indexed = true, bool $multiValued = false): void64 ビット浮動小数点フィールド。$multiValued = true で浮動小数点配列を受け付け(範囲クエリは “any match”)。
addBooleanField(string $name, bool $stored = true, bool $indexed = true): voidブールフィールド。
addBytesField(string $name, bool $stored = true): void生バイトフィールド。
addGeoField(string $name, bool $stored = true, bool $indexed = true): void地理座標フィールド(緯度/経度)。
addGeo3dField(string $name, bool $stored = true, bool $indexed = true): void3D ECEF カルテシアン座標フィールド(x, y, z はメートル)。詳細は Geo3d の概念
addDatetimeField(string $name, bool $stored = true, bool $indexed = true): voidUTC 日時フィールド。
addHnswField(string $name, int $dimension, ?string $distance = "cosine", int $m = 16, int $efConstruction = 200, ?string $embedder = null): voidHNSW 近似最近傍ベクトルフィールド。
addFlatField(string $name, int $dimension, ?string $distance = "cosine", ?string $embedder = null): voidFlat(総当たり)ベクトルフィールド。
addIvfField(string $name, int $dimension, ?string $distance = "cosine", int $nClusters = 100, int $nProbe = 1, ?string $embedder = null): voidIVF 近似最近傍ベクトルフィールド。

その他のメソッド

メソッド説明
addEmbedder(string $name, array $config): void名前付きエンベダー定義を登録します。$config"type" キーを持つ連想配列です(下記参照)。
setDefaultFields(array $fieldNames): voidクエリでフィールドが指定されていない場合に使用するデフォルトフィールドを設定します。$fieldNames は文字列の配列です。
setDynamicFieldPolicy(string $policy): void未宣言フィールドの扱いを設定します。$policy"strict" / "dynamic"(デフォルト)/ "ignore"。詳細は下記を参照。
dynamicFieldPolicy(): string現在のポリシーを小文字の文字列で返します。
fieldNames(): arrayこのスキーマに定義されたフィールド名のリストを返します。

Dynamic field policy(動的フィールドポリシー)

ドキュメントに含まれるがスキーマに宣言されていないフィールドの扱いを制御します:

  • "strict" — ドキュメントを拒否
  • "dynamic"(デフォルト)— 各未宣言フィールドの型を推論してスキーマに追加。警告: integer フィールドに入ってきた float 値は静かに切り捨てられます(3.143)。厳密さが必要なら "strict" を使用してください
  • "ignore" — 未宣言フィールドを静かに破棄

詳細な挙動マトリクスは スキーマとフィールド を参照してください。

エンベダータイプ

"type"必須キーFeature Flag
"precomputed"(常に利用可能)
"candle_bert""model"embeddings-candle
"candle_clip""model"embeddings-multimodal
"openai""model"embeddings-openai

距離メトリクス

説明
"cosine"コサイン類似度(デフォルト)
"euclidean"ユークリッド距離
"dot_product"内積
"manhattan"マンハッタン距離
"angular"角度距離

クエリクラス

TermQuery

new \Laurus\TermQuery(string $field, string $term)

指定フィールドに完全一致する語句を含むドキュメントを検索します。

PhraseQuery

new \Laurus\PhraseQuery(string $field, array $terms)

指定した語句が順序どおりに含まれるドキュメントを検索します。$terms は文字列の配列です。

FuzzyQuery

new \Laurus\FuzzyQuery(string $field, string $term, int $maxEdits = 2)

編集距離が $maxEdits 以内の近似一致を検索します。

WildcardQuery

new \Laurus\WildcardQuery(string $field, string $pattern)

ワイルドカードパターン検索。* は任意の文字列、? は任意の1文字に一致します。

NumericRangeQuery

new \Laurus\NumericRangeQuery(string $field, mixed $min, mixed $max, ?string $numericType = "integer")

[$min, $max] の範囲内の数値を検索します。開いた境界には null を指定します。$numericType には "integer" または "float" を設定します。

GeoDistanceQuery

\Laurus\GeoDistanceQuery::withinRadius(
    string $field, float $lat, float $lon, float $distanceM,
): GeoDistanceQuery

地理的距離検索(半径指定)。指定した地点から $distanceM メートル以内の (lat, lon) 座標を持つドキュメントを返します。

GeoBoundingBoxQuery

\Laurus\GeoBoundingBoxQuery::withinBoundingBox(
    string $field,
    float $minLat, float $minLon,
    float $maxLat, float $maxLon,
): GeoBoundingBoxQuery

地理的範囲(バウンディングボックス)検索。軸並行 [$minLat, $maxLat] × [$minLon, $maxLon] 内の (lat, lon) 座標を持つドキュメントを返します。

Geo3dDistanceQuery

\Laurus\Geo3dDistanceQuery::withinSphere(
    string $field,
    float $x, float $y, float $z,
    float $distanceM,
): Geo3dDistanceQuery

3D ECEF 座標フィールドへの球距離検索。中心 (x, y, z) から $distanceM メートル以内 の座標を持つドキュメントを返します。ECEF の理論については Geo3d の概念 を参照。

Geo3dBoundingBoxQuery

\Laurus\Geo3dBoundingBoxQuery::withinBox(
    string $field,
    float $minX, float $minY, float $minZ,
    float $maxX, float $maxY, float $maxZ,
): Geo3dBoundingBoxQuery

軸並行 3D 範囲(AABB)検索。

Geo3dNearestQuery

\Laurus\Geo3dNearestQuery::kNearest(
    string $field,
    float $x, float $y, float $z,
    int $k,
    ?float $initialRadiusM = null,
    ?float $maxRadiusM = null,
): Geo3dNearestQuery

3D ECEF 座標フィールドへの k 最近傍検索。$initialRadiusM / $maxRadiusM (オプション)で反復拡張サーチの探索コーンを調整できます。

BooleanQuery

$bq = new \Laurus\BooleanQuery();
$bq->must($query);
$bq->should($query);
$bq->mustNot($query);

複合ブールクエリ。must 節はすべて一致する必要があり、mustNot 節は一致してはなりません。should 節はスコアリングに寄与し、must 節が無い場合は少なくとも1つが一致する必要があります。

SpanQuery

// 単一語句
\Laurus\SpanQuery::term(string $field, string $term): SpanQuery

// Near: slop 位置以内の語句
\Laurus\SpanQuery::near(string $field, array $terms, int $slop = 0, bool $ordered = true): SpanQuery

// NearSpans: slop 位置以内のネストされた SpanQuery 句
\Laurus\SpanQuery::nearSpans(string $field, array $clauses, int $slop = 0, bool $ordered = true): SpanQuery

// Containing: big スパンが little スパンを含む
\Laurus\SpanQuery::containing(string $field, SpanQuery $big, SpanQuery $little): SpanQuery

// Within: 最大距離での include スパンと exclude スパン
\Laurus\SpanQuery::within(string $field, SpanQuery $include, SpanQuery $exclude, int $distance): SpanQuery

位置・近接スパンクエリ。near は語句文字列の配列を受け取り、nearSpans は ネスト式のために SpanQuery オブジェクトの配列を受け取ります(各句のフィールド は外側の $field に再ルートされます)。

VectorQuery

new \Laurus\VectorQuery(string $field, array $vector)

事前計算済みエンベディングベクトルを使った近似最近傍検索を行います。$vector は Float の配列です。

VectorTextQuery

new \Laurus\VectorTextQuery(string $field, string $text)

クエリ時に $text をエンベディングに変換してベクトル検索を行います。インデックスにエンベダーの設定が必要です。


SearchRequest

高度な制御が必要な場合の完全なリクエストクラスです。

new \Laurus\SearchRequest(
    mixed $query = null,
    mixed $lexicalQuery = null,
    mixed $vectorQuery = null,
    mixed $filterQuery = null,
    mixed $fusion = null,
    int $limit = 10,
    int $offset = 0,
)
パラメータ説明
$queryDSL 文字列または単一クエリオブジェクト。$lexicalQuery / $vectorQuery と排他的。
$lexicalQuery明示的なハイブリッド検索の Lexical コンポーネント。
$vectorQuery明示的なハイブリッド検索の Vector コンポーネント。
$filterQueryスコアリング後に適用する Lexical フィルター。
$fusionフュージョンアルゴリズム(RRF または WeightedSum)。両コンポーネント指定時のデフォルトは RRF(k: 60)
$limit最大結果件数(デフォルト 10)。
$offsetページネーションオフセット(デフォルト 0)。

SearchResult

Index->search() が返すクラスです。

$result->getId()        // string   -- 外部ドキュメント識別子
$result->getScore()     // float    -- 関連性スコア
$result->getDocument()  // array|null -- 取得されたフィールド値。stored=false の場合は null

フュージョンアルゴリズム

RRF

new \Laurus\RRF(float $k = 60.0)

逆順位フュージョン(Reciprocal Rank Fusion)。Lexical と Vector の結果リストを順位位置によってマージします。$k は平滑化定数で、値が大きいほど上位ランクの影響が小さくなります。

WeightedSum

new \Laurus\WeightedSum(float $lexicalWeight = 0.5, float $vectorWeight = 0.5)

両スコアリストをそれぞれ正規化した後、$lexicalWeight * lexical_score + $vectorWeight * vector_score として結合します。


テキスト解析

SynonymDictionary

$dict = new \Laurus\SynonymDictionary();
$dict->addSynonymGroup(["fast", "quick", "rapid"]);

同義語グループの辞書です。グループ内のすべての語句は互いの同義語として扱われます。

WhitespaceTokenizer

$tokenizer = new \Laurus\WhitespaceTokenizer();
$tokens = $tokenizer->tokenize("hello world");

空白で分割してテキストをトークン化し、Token オブジェクトの配列を返します。

SynonymGraphFilter

new \Laurus\SynonymGraphFilter(SynonymDictionary $dictionary, bool $keepOriginal = true, float $boost = 1.0)
パラメータ説明
$dictionary同義語グループのソース。
$keepOriginaltrue(デフォルト)の場合は元のトークンも同義語と並べて保持します。
$boost挿入される同義語トークンに適用されるスコアブースト(デフォルト 1.0)。
$filter = new \Laurus\SynonymGraphFilter($dictionary, true, 1.0);
$expanded = $filter->apply($tokens);

SynonymDictionary の同義語でトークンを展開するトークンフィルターです。

Token

$token->getText()               // string  -- トークンテキスト
$token->getPosition()           // int     -- トークンストリーム内の位置
$token->getStartOffset()        // int     -- 元テキスト内の文字開始オフセット
$token->getEndOffset()          // int     -- 元テキスト内の文字終了オフセット
$token->getBoost()              // float   -- スコアブースト係数(1.0 = 調整なし)
$token->isStopped()             // bool    -- ストップフィルターによって除去されたかどうか
$token->getPositionIncrement()  // int     -- 前のトークンの位置との差分
$token->getPositionLength()     // int     -- このトークンがカバーする位置数

フィールド値の型マッピング

PHP の値は自動的に Laurus の DataValue 型に変換されます:

PHP 型Laurus 型備考
nullNull
true / falseBool
intInt64
floatFloat64
stringText
array(数値)Vector要素は f32 に変換
array"lat", "lon"Geo2 つの float
array"x", "y", "z"GeoEcef3 つの float 値(メートル単位、3D ECEF 直交座標)
string(ISO 8601)DateTimeISO 8601 形式からパース