Rust MeiliSearch索引设置宏库meilisearch-index-setting-macro的使用,简化搜索引擎索引配置与自定义
Rust MeiliSearch索引设置宏库meilisearch-index-setting-macro的使用
meilisearch-index-setting-macro是一个简化MeiliSearch搜索引擎索引配置与自定义的Rust宏库。
安装
在项目目录中运行以下Cargo命令:
cargo add meilisearch-index-setting-macro
或者在Cargo.toml中添加以下行:
meilisearch-index-setting-macro = "0.29.1"
使用示例
下面是一个完整的使用示例,展示如何使用该宏库简化MeiliSearch索引配置:
use meilisearch_index_setting_macro::index_settings;
use serde::{Serialize, Deserialize};
// 定义一个结构体来表示文档
#[derive(Serialize, Deserialize)]
struct Book {
id: String,
title: String,
author: String,
description: String,
genre: Vec<String>,
published_at: chrono::NaiveDate,
rating: f64,
}
// 使用index_settings宏定义索引设置
index_settings! {
BookIndex {
// 主键字段
primary_key: "id",
// 搜索字段
searchable_fields: [
"title",
"author",
"description",
"genre"
],
// 过滤字段
filterable_fields: [
"author",
"genre",
"published_at",
"rating"
],
// 排序字段
sortable_fields: [
"published_at",
"rating"
],
// 显示字段
displayed_fields: [
"title",
"author",
"description",
"genre",
"published_at"
],
// 停用词
stop_words: [
"the", "a", "an", "of", "to", "in", "for", "on", "with", "at"
],
// 同义词
synonyms: {
"book": ["novel", "publication"],
"writer": ["author", "novelist"]
},
// 排名规则
ranking_rules: [
"words",
"typo",
"proximity",
"attribute",
"sort",
"exactness"
],
// 分词器配置
typo_tolerance: {
enabled: true,
min_word_size_for_typos: {
one_typo: 5,
two_typos: 9
}
}
}
}
// 使用生成的索引设置
async fn configure_index(client: &meilisearch_sdk::Client) -> Result<(), meilisearch_sdk::Error> {
let index = client.index("books");
// 应用我们定义的设置
BookIndex::apply_settings(&index).await?;
Ok(())
}
完整示例代码
use meilisearch_index_setting_macro::index_settings;
use serde::{Serialize, Deserialize};
use meilisearch_sdk::Client;
use chrono::NaiveDate;
// 1. 定义数据结构
#[derive(Debug, Serialize, Deserialize)]
struct Movie {
id: String,
title: String,
director: String,
year: i32,
genres: Vec<String>,
rating: f64,
duration: i32, // 分钟
}
// 2. 使用宏定义索引设置
index_settings! {
MovieIndex {
primary_key: "id",
searchable_fields: [
"title",
"director",
"genres"
],
filterable_fields: [
"director",
"year",
"genres",
"rating",
"duration"
],
sortable_fields: [
"year",
"rating",
"duration"
],
displayed_fields: [
"title",
"director",
"year",
"genres",
"rating"
],
stop_words: [
"the", "a", "an", "and", "or", "in", "of"
],
synonyms: {
"movie": ["film", "picture"],
"director": ["filmmaker"]
},
ranking_rules: [
"words",
"typo",
"proximity",
"attribute",
"sort",
"exactness"
],
typo_tolerance: {
enabled: true,
min_word_size_for_typos: {
one_typo: 4,
two_typos: 8
}
}
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 3. 创建MeiliSearch客户端
let client = Client::new("http://localhost:7700", "masterKey");
// 4. 配置索引
let movies = client.index("movies");
MovieIndex::apply_settings(&movies).await?;
// 5. 添加文档
let movie_docs = vec![
Movie {
id: "1".to_string(),
title: "The Shawshank Redemption".to_string(),
director: "Frank Darabont".to_string(),
year: 1994,
genres: vec!["Drama".to_string()],
rating: 9.3,
duration: 142,
},
Movie {
id: "2".to_string(),
title: "The Godfather".to_string(),
director: "Francis Ford Coppola".to_string(),
year: 1972,
genres: vec!["Crime".to_string(), "Drama".to_string()],
rating: 9.2,
duration: 175,
},
];
movies.add_documents(&movie_docs, Some("id")).await?;
println!("索引配置完成并已添加文档!");
Ok(())
}
这个宏库主要提供了以下功能:
- 简化索引设置的定义过程
- 提供类型安全的配置方式
- 自动生成应用设置的代码
- 支持所有主要的MeiliSearch索引配置选项
使用该宏库可以大大减少手动配置索引所需的样板代码,同时保持配置的类型安全性和可维护性。
1 回复
meilisearch-index-setting-macro - 简化MeiliSearch索引配置的Rust宏库
meilisearch-index-setting-macro
是一个用于简化MeiliSearch搜索引擎索引配置的Rust宏库,它通过过程宏提供类型安全的索引设置方式。
主要功能
- 简化MeiliSearch索引设置过程
- 提供类型安全的配置方式
- 减少样板代码
- 支持自定义配置选项
安装
在Cargo.toml中添加依赖:
[dependencies]
meilisearch-index-setting-macro = "0.1"
meilisearch-sdk = "0.20"
完整示例demo
以下是使用meilisearch-index-setting-macro
的完整示例:
use meilisearch_index_setting_macro::index_settings;
use meilisearch_sdk::{client::Client, indexes::Index};
use serde::{Serialize, Deserialize};
// 1. 定义索引结构
#[index_settings]
#[derive(Debug, Serialize, Deserialize)]
struct Product {
id: String,
#[searchable]
name: String,
#[filterable, sortable]
price: f64,
#[filterable]
category: String,
#[searchable]
description: String,
#[filterable, sortable]
stock: u32,
#[synonyms("phone" = ["mobile", "cellphone"])]
tags: Vec<String>,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 2. 创建MeiliSearch客户端
let client = Client::new("http://localhost:7700", "masterKey");
// 3. 使用宏生成的代码创建索引
let index = Product::create_index(&client, "products").await?;
// 4. 准备要添加的文档
let products = vec![
Product {
id: "1".to_string(),
name: "Smartphone X".to_string(),
price: 999.99,
category: "Electronics".to_string(),
description: "Latest smartphone with advanced features".to_string(),
stock: 100,
tags: vec!["phone".to_string(), "tech".to_string()],
},
Product {
id: "2".to_string(),
name: "Wireless Headphones".to_string(),
price: 199.99,
category: "Audio".to_string(),
description: "Noise cancelling wireless headphones".to_string(),
stock: 50,
tags: vec!["audio".to_string(), "wireless".to_string()],
},
];
// 5. 添加文档到索引
index.add_documents(&products, Some("id")).await?;
// 6. 搜索示例
let search_results = index.search()
.with_query("phone")
.execute()
.await?;
println!("搜索到 {} 个结果", search_results.hits.len());
Ok(())
}
代码说明
#[index_settings]
宏会自动为结构体生成创建索引所需的代码#[searchable]
标记的字段会被设置为可搜索#[filterable]
和#[sortable]
标记的字段可以用于过滤和排序#[synonyms]
可以为字段定义同义词create_index
方法是宏自动生成的,用于创建并配置索引- 添加文档时需要指定主键字段(本例中为"id")
高级用法示例
#[index_settings(
index_name = "ecommerce_products",
primary_key = "sku_code",
ranking_rules = "words,typo,proximity,attribute,exactness"
)]
#[derive(Debug, Serialize, Deserialize)]
struct EcommerceProduct {
sku_code: String,
#[searchable(ranking_rules = "words,typo,proximity")]
name: String,
#[filterable, sortable]
price: f64,
#[filterable]
categories: Vec<String>,
#[searchable, filterable]
brand: String,
#[synonyms("TV" = ["Television", "Smart TV"])]
tags: Vec<String>,
}
注意事项
- 确保MeiliSearch服务正在运行
- 需要配合
meilisearch-sdk
使用 - 结构体需要实现
Serialize
和Deserialize
trait - 对于大型数据集,建议分批添加文档
- 索引设置会在编译时生成,修改设置后需要重新编译