扩展现有的搜索和查询功能
有关查询扩展器和评分函数扩展的详细信息
RediSearch 支持扩展机制,类似于 Redis 支持模块。API 目前非常基础,并且还不支持在运行服务器上动态加载扩展。相反,扩展必须用 C(或具有 C 接口的语言)编写,并编译成可以在启动时加载的动态库。
目前有两种扩展 API
- **查询扩展器**,其作用是扩展查询令牌(即词干提取器)。
- **评分函数**,其作用是在查询时对搜索结果进行排名。
注册和加载扩展
扩展应该编译成动态库文件(例如 .so
文件),并在初始化期间加载到 RediSearch 模块中。
编译
Extensions should be compiled and linked as dynamic libraries. An example Makefile for an extension [can be found here](https://github.com/RediSearch/RediSearch/blob/master/tests/ctests/ext-example/Makefile).
That folder also contains an example extension that is used for testing and can be taken as a skeleton for implementing your own extension.
加载
Loading an extension is done by appending `EXTLOAD {path/to/ext.so}` after the `loadmodule` configuration directive when loading the RediSearch module. For example:
```sh
$ redis-server --loadmodule ./redisearch.so EXTLOAD ./ext/my_extension.so
```
This causes the RediSearch module to automatically load the extension and register its expanders and scorers.
初始化扩展
扩展的入口点是一个具有以下签名的函数
int RS_ExtensionInit(RSExtensionCtx *ctx);
加载扩展时,RediSearch 会查找此函数并调用它。此函数负责注册和初始化扩展器和评分器。
它应该在错误时返回 REDISEARCH_ERR,在成功时返回 REDISEARCH_OK。
示例 init 函数
#include <redisearch.h> //must be in the include path
int RS_ExtensionInit(RSExtensionCtx *ctx) {
/* Register a scoring function with an alias my_scorer and no special private data and free function */
if (ctx->RegisterScoringFunction("my_scorer", MyCustomScorer, NULL, NULL) == REDISEARCH_ERR) {
return REDISEARCH_ERR;
}
/* Register a query expander */
if (ctx->RegisterQueryExpander("my_expander", MyExpander, NULL, NULL) ==
REDISEARCH_ERR) {
return REDISEARCH_ERR;
}
return REDISEARCH_OK;
}
调用您的自定义函数
在执行查询时,您可以通过使用给定的别名指定 SCORER 或 EXPANDER 参数来使用您的评分器或扩展器。例如
FT.SEARCH my_index "foo bar" EXPANDER my_expander SCORER my_scorer
注意:扩展器和评分器别名是区分大小写的。
查询扩展器 API
仅支持基本查询扩展,一次一个标记。扩展器可以决定用它想要的任意数量的标记来扩展任何给定的标记,这些标记将在查询时进行并集合并。
扩展器的 API 如下
#include <redisearch.h> //must be in the include path
void MyQueryExpander(RSQueryExpanderCtx *ctx, RSToken *token) {
...
}
RSQueryExpanderCtx
RSQueryExpanderCtx
是一个上下文,包含扩展的私有数据,以及一个扩展查询的回调方法。它定义为
typedef struct RSQueryExpanderCtx {
/* Opaque query object used internally by the engine, and should not be accessed */
struct RSQuery *query;
/* Opaque query node object used internally by the engine, and should not be accessed */
struct RSQueryNode **currentNode;
/* Private data of the extension, set on extension initialization */
void *privdata;
/* The language of the query, defaults to "english" */
const char *language;
/* ExpandToken allows the user to add an expansion of the token in the query, that will be
* union-merged with the given token in query time. str is the expanded string, len is its length,
* and flags is a 32 bit flag mask that can be used by the extension to set private information on
* the token */
void (*ExpandToken)(struct RSQueryExpanderCtx *ctx, const char *str, size_t len,
RSTokenFlags flags);
/* SetPayload allows the query expander to set GLOBAL payload on the query (not unique per token)
*/
void (*SetPayload)(struct RSQueryExpanderCtx *ctx, RSPayload payload);
} RSQueryExpanderCtx;
RSToken
RSToken
代表一个要扩展的单个查询标记,定义如下
/* A token in the query. The expanders receive query tokens and can expand the query with more query
* tokens */
typedef struct {
/* The token string - which may or may not be NULL terminated */
const char *str;
/* The token length */
size_t len;
/* 1 if the token is the result of query expansion */
uint8_t expanded:1;
/* Extension specific token flags that can be examined later by the scoring function */
RSTokenFlags flags;
} RSToken;
评分函数 API
对于最终排名,评分函数会分析查询检索到的每个文档,不仅考虑触发文档检索的词语,还会考虑元数据,如文档的先验得分、长度等。
由于评分函数会对每个文档进行评估,可能数百万次,而且 Redis 是单线程的,因此它必须尽可能快地工作并进行高度优化。
评分函数应用于每个潜在结果的每个文档,并使用以下签名实现
double MyScoringFunction(RSScoringFunctionCtx *ctx, RSIndexResult *res,
RSDocumentMetadata *dmd, double minScore);
RSScoringFunctionCtx
是一个上下文,它实现了一些辅助方法。
RSIndexResult
是包含文档 ID、频率、词语和偏移量的结果信息。
RSDocumentMetadata
是一个对象,保存有关文档的全局信息,例如其推测得分。
minScore
是将产生与搜索相关的结果的最小得分。它可用于在中途或之前停止处理,甚至在处理开始之前停止处理。
函数的返回值是一个double
,表示结果的最终得分。返回 0 会导致结果被计算,但如果有得分大于 0 的结果,它们将出现在它之上。要完全过滤掉结果而不将其计入总数,评分器应返回特殊值RS_SCORE_FILTEROUT
,该值在内部设置为负无穷大,或 -1/0。
RSScoringFunctionCtx
这是一个包含以下成员的对象
void *privdata
:指向扩展在初始化时设置的对象的指针。RSPayload payload*
:一个由查询扩展器或客户端设置的有效负载对象。int GetSlop(RSIndexResult *res)*
:一个回调方法,它产生查询词语之间总的最小距离。这可以用来优先考虑斜率较小且词语彼此更靠近的结果。
RSIndexResult
这是一个对象,保存有关索引中当前结果的信息,它是导致当前文档被认为是有效结果的所有词语的聚合。有关详细信息,请参阅redisearch.h
。
RSDocumentMetadata
这是一个对象,描述有关由评分函数评估的文档的全局信息,与当前查询无关。
示例查询扩展器
此示例查询扩展器使用 term foo 扩展每个标记
#include <redisearch.h> //must be in the include path
void DummyExpander(RSQueryExpanderCtx *ctx, RSToken *token) {
ctx->ExpandToken(ctx, strdup("foo"), strlen("foo"), 0x1337);
}
示例评分函数
这是一个实际的评分函数,它计算文档的 TF-IDF,将其乘以文档得分,然后除以斜率
#include <redisearch.h> //must be in the include path
double TFIDFScorer(RSScoringFunctionCtx *ctx, RSIndexResult *h, RSDocumentMetadata *dmd,
double minScore) {
// no need to evaluate documents with score 0
if (dmd->score == 0) return 0;
// calculate sum(tf-idf) for each term in the result
double tfidf = 0;
for (int i = 0; i < h->numRecords; i++) {
// take the term frequency and multiply by the term IDF, add that to the total
tfidf += (float)h->records[i].freq * (h->records[i].term ? h->records[i].term->idf : 0);
}
// normalize by the maximal frequency of any term in the document
tfidf /= (double)dmd->maxFreq;
// multiply by the document score (between 0 and 1)
tfidf *= dmd->score;
// no need to factor the slop if tfidf is already below minimal score
if (tfidf < minScore) {
return 0;
}
// get the slop and divide the result by it, making sure we prefer results with closer terms
tfidf /= (double)ctx->GetSlop(h);
return tfidf;
}