全面解析MeiliSearch及其Go语言实现

前言

随着互联网的发展和数字化进程的加速,无论是企业还是个人用户,都需要面对海量的信息。在这个背景下,搜索技术的重要性日益凸显。MeiliSearch 是一款开源搜索引擎,它的出现为开发者提供了一个高效、灵活的选择。本文将从多个角度探讨 MeiliSearch 的特性、使用方法及其实现原理,并通过 Go 语言示例展示如何构建一个高性能的搜索系统。

一、MeiliSearch 特性

MeiliSearch 之所以受到欢迎,主要是因为它具有以下几个关键特性:

  • 易用性:MeiliSearch 的设计初衷就是简化搜索集成流程,无论是安装、配置还是使用都非常直观。
  • 高性能:它采用了高效的搜索算法和数据结构,能够在毫秒级内返回搜索结果。
  • 高度可定制性:用户可以根据具体需求调整搜索算法的权重,甚至定义同义词和停用词等。
  • 多语言支持:MeiliSearch 内置了对多种语言的支持,这对于全球化的产品来说非常有用。
  • 实时性:索引更新几乎是实时的,这意味着任何新的数据都可以立刻被搜索到。

1.1 核心功能

文档索引

索引是搜索引擎的核心,MeiliSearch 支持文档级别的索引,这意味着每个独立的条目都可以被单独索引。通过 RESTful API,你可以轻松地添加、删除或更新索引中的文档。

排序与过滤

MeiliSearch 允许你在搜索查询中指定排序规则和过滤条件,这使得你可以根据用户的偏好或业务逻辑来组织搜索结果。

同义词与停用词

为了提高搜索的准确性,MeiliSearch 支持自定义同义词和停用词。同义词可以用来处理多义词或多写法的情况,而停用词则有助于减少噪音词汇的影响。

高级搜索语法

除了基本的全文搜索之外,MeiliSearch 还支持布尔搜索、模糊搜索等多种搜索语法,这让搜索查询变得更加灵活和强大。

1.2 技术栈

MeiliSearch 是基于 Rust 语言开发的,这赋予了它极高的性能和稳定性。Rust 的内存安全特性也使得 MeiliSearch 在处理大量数据时更加可靠。

二、安装与设置

2.1 前提条件

  • 一台运行着 Linux、macOS 或 Windows 的计算机。
  • Docker。
  • Go 语言环境(推荐版本:1.17 或更高)。

2.2 安装过程

通过 Docker 安装

如果你的机器上已经安装了 Docker,那么可以通过以下命令快速启动 MeiliSearch:

docker pull getmeili/meilisearch
docker run -it --rm -p 7700:7700 -e MEILI_ENV='development' -e MEILI_MASTER_KEY='3EX4QpUfpqX6XfOIks-qWg6tvpQxdWmr7CxHUN4GgaA' -e MEILI_SCHEDULE_SNAPSHOT=60 -v /user/local/src/meilisearch/data:/meili_data getmeili/meilisearch:v1.9

docker run: 运行一个容器。
-it: 以交互模式 (interactive) 运行容器,并分配一个伪输入终端 (TTY)。
--rm: 当容器停止时自动删除容器。
-p 7700:7700: 将主机的 7700 端口映射到容器内的 7700 端口,这样可以从外部网络访问容器内的服务。
-e MEILI_ENV='development': 设置环境变量 MEILI_ENV 为 development,这意味着 MeiliSearch 将以开发模式运行。
-e MEILI_MASTER_KEY='3EX4QpUfpqX6XfOIks-qWg6tvpQxdWmr7CxHUN4GgaA': 设置主密钥 (MEILI_MASTER_KEY),用于管理所有 API 调用。
-e MEILI_SCHEDULE_SNAPSHOT=60: 设置定期快照的时间间隔为 60 秒,这表示每分钟 MeiliSearch 将会创建一个快照。
-v /user/local/src/meilisearch/data:/meili_data: 将主机上的 /user/local/src/meilisearch/data 目录挂载到容器内的 /meili_data 目录,这样可以持久化 MeiliSearch 的数据。
getmeili/meilisearch:v1.9: 指定要运行的 Docker 镜像,标签为 v1.9。

这条命令将会下载最新的 MeiliSearch 镜像并启动一个容器,在你的机器上开放 7700 端口。

本地安装

如果你希望直接在本地安装 MeiliSearch,可以使用以下命令:

curl -L https://install.meilisearch.com | sh

这条命令会下载并安装 MeiliSearch 到你的系统中。

2.3 配置与管理

API 密钥

为了保护你的数据安全,MeiliSearch 允许生成 API 密钥来限制对索引的访问。你可以通过 API 创建不同的密钥,并为每个密钥分配不同的权限。

curl 'http://localhost:7700/apikeys' -X POST \
    -H 'Content-Type: application/json' \
    -d '{"description":"example API key", "actions":["search"], "indexes":["*"]}'

索引管理

MeiliSearch 通过索引来组织数据。你可以创建多个索引,每个索引对应不同类型的数据。创建索引的命令如下:

curl 'http://localhost:7700/indexes' -X POST \
    -H 'Content-Type: application/json' \
    -d '{"uid":"myFirstIndex"}'

一旦索引被创建,你就可以开始向其中添加数据了。

日志与监控

MeiliSearch 提供了详细的日志记录功能,这对于调试和维护非常有帮助。你可以通过查看容器的日志来了解 MeiliSearch 的运行状态:

docker logs <container-id>

三、使用 Go 语言与 MeiliSearch 交互

Go 语言以其简洁的语法、高效的性能和良好的并发支持而闻名,这使得它成为与 MeiliSearch 进行交互的理想选择。下面是一些使用 Go 语言操作 MeiliSearch 的示例。

3.1 示例代码

3.1.1 创建索引

package main

import (
	"fmt"
	"github.com/meilisearch/meilisearch-go"
)

func main() {
	// 创建 MeiliSearch 客户端实例
	client := meilisearch.NewClient(
		meilisearch.ClientConfig{
			Host:   "http://localhost:7700",
			APIKey: "3EX4QpUfpqX6XfOIks-qWg6tvpQxdWmr7CxHUN4GgaA", // 如果使用了API密钥
		},
	)

	// 创建索引
	task, err := client.CreateIndex(&meilisearch.IndexConfig{Uid: "movies"})
	if err != nil {
		fmt.Println("Error creating index:", err)
		return
	}

	fmt.Printf("Created index response : %+v\n", *task)
}

3.1.2 搜索文档

为了方便大家有大量数据,这里使用官方提供的 movie 数据,大家点击下载使用。

package main

import (
	"encoding/json"
	"fmt"
	"github.com/meilisearch/meilisearch-go"
	"log"
	"os"
)

func main() {
	// 创建 MeiliSearch 客户端实例
	client := meilisearch.NewClient(
		meilisearch.ClientConfig{
			Host:   "http://localhost:7700",
			APIKey: "3EX4QpUfpqX6XfOIks-qWg6tvpQxdWmr7CxHUN4GgaA", // 如果使用了API密钥
		},
	)

	// 搜索文档
	resp, err := client.Index("movies").Search("Star Wars", &meilisearch.SearchRequest{Limit: 2})
	if err != nil {
		log.Fatalf("Error searching: %v", err)
	}

	// 输出搜索结果
	for _, movie := range resp.Hits {
		fmt.Printf("%+v\n", movie)
	}
	// map[genres:[Adventure Action Science Fiction] id:11 overview:Princess Leia is captured and held hostage by the evil Imperial forces in their effort to take over the galactic Empire. Venturesome Luke Skywalker and dashing captain Han Solo team together with the loveable robot duo R2-D2 and C-3PO to rescue the beautiful princess and restore peace and justice in the Empire. poster:https://image.tmdb.org/t/p/w500/6FfCtAuVAW8XJjZ7eWeLibRLWTw.jpg release_date:2.333664e+08 title:Star Wars]
	// map[genres:[Adventure Action Science Fiction] id:1893 overview:Anakin Skywalker, a young slave strong with the Force, is discovered on Tatooine. Meanwhile, the evil Sith have returned, enacting their plot for revenge against the Jedi. poster:https://image.tmdb.org/t/p/w500/6wkfovpn7Eq8dYNKaG5PY3q2oq6.jpg release_date:9.27072e+08 title:Star Wars: Episode I - The Phantom Menace]
}

访问 meilisearch 服务可以查看添加的文档数据:


3.2 高级搜索

除了基本的全文搜索外,MeiliSearch 还支持多种高级搜索功能,例如过滤、分页和高亮显示等。

3.2.1 过滤搜索

package main

import (
	"encoding/json"
	"fmt"
	"github.com/meilisearch/meilisearch-go"
	"log"
	"os"
)

func main() {
	// 创建 MeiliSearch 客户端实例
	client := meilisearch.NewClient(
		meilisearch.ClientConfig{
			Host:   "http://localhost:7700",
			APIKey: "3EX4QpUfpqX6XfOIks-qWg6tvpQxdWmr7CxHUN4GgaA", // 如果使用了API密钥
		},
	)

	// 更新过滤器(请求之后等待一段时间才生效)
	//_, err := client.Index("movies").UpdateFilterableAttributes(&[]string{
	//	"id",
	//	"title",
	//	"overview",
	//})
	//if err != nil {
	//	log.Fatalf("Error updating filterable attributes: %v", err)
	//}

	resp, err := client.Index("movies").Search("star", &meilisearch.SearchRequest{
		Filter: "id > 100 AND (NOT title = 'Star Trek: The Motion Picture')",
	})
	if err != nil {
		log.Fatalf("Error searching: %v", err)
	}

	// 输出搜索结果
	for _, movie := range resp.Hits {
		fmt.Printf("%+v\n", movie)
	}
	// map[genres:[Action Adventure Science Fiction Thriller] id:154 overview:It is the 23rd century. The Federation Starship U.S.S. Enterprise™ is on routine training maneuvers and Admiral James T. Kirk (William Shatner) seems resigned to the fact that this inspection may well be the last space mission of his career. But Khan is back. Aided by his exiled band of genetic supermen, Khan (Ricardo Montalban) - brilliant renegade of 20th century Earth - has raided Space Station Regula One, stolen a top secret device called Project Genesis, wrested control of another Federation Starship and sets out in pursuit of the Enterprise, determined to let nothing stand in the way of his mission: kill Admiral Kirk... even if it means universal Armageddon. poster:https://image.tmdb.org/t/p/w500/uPyLsKl8Z0LOoxeaFXsY5MxhR5s.jpg release_date:3.919968e+08 title:Star Trek II: The Wrath of Khan]
	// map[genres:[Science Fiction Action Adventure Thriller] id:157 overview:Admiral Kirk and his bridge crew risk their careers stealing the decommissioned Enterprise to return to the restricted Genesis planet to recover Spock's body. poster:https://image.tmdb.org/t/p/w500/yqEj0oPfKBMCz7YcCARHDgH7VFm.jpg release_date:4.54896e+08 title:Star Trek III: The Search for Spock]
	// ......
}

3.2.2 搜索排序

默认情况下,Meilisearch 重点根据结果的相关性对结果进行排序。您可以更改此排序行为,以便用户可以在搜索时决定他们想要首先看到的结果类型。

package main

import (
	"encoding/json"
	"fmt"
	"github.com/meilisearch/meilisearch-go"
	"log"
	"os"
)

func main() {
	// 创建 MeiliSearch 客户端实例
	client := meilisearch.NewClient(
		meilisearch.ClientConfig{
			Host:   "http://localhost:7700",
			APIKey: "3EX4QpUfpqX6XfOIks-qWg6tvpQxdWmr7CxHUN4GgaA", // 如果使用了API密钥
		},
	)

	// 更新排序过滤器(请求之后等待一段时间才生效)
	//_, err := client.Index("movies").UpdateSortableAttributes(&[]string{
	//	"id",
	//})
	//if err != nil {
	//	log.Fatalf("Error updating filterable attributes: %v", err)
	//}

	resp, err := client.Index("movies").Search("", &meilisearch.SearchRequest{
		Sort: []string{
			"id:desc",
		},
	})
	if err != nil {
		log.Fatalf("Error searching: %v", err)
	}

	// 输出搜索结果
	for _, movie := range resp.Hits {
		fmt.Printf("%+v\n", movie)
	}
	// map[genres:[Crime Drama Thriller] id:460071 overview:Massachusetts, 1892. An unmarried woman of 32 and a social outcast, Lizzie lives a claustrophobic life under her father's cold and domineering control. When Bridget Sullivan, a young maid, comes to work for the family, Lizzie finds a sympathetic, kindred spirit, and a secret intimacy soon blossoms into a wicked plan. poster:https://image.tmdb.org/t/p/w500/z2iuBcwznen3kC9z4LeOzBSz1BB.jpg release_date:1.5368832e+09 title:Lizzie]
	// map[genres:[Drama] id:460070 overview:A young woman named Savannah Knoop spends six years pretending to be a transgender writer named JT Leroy, the made-up literary persona of her sister-in-law. poster:https://image.tmdb.org/t/p/w500/43ffZhMCWQhzMneGP4kDWoPV48X.jpg release_date:1.5562368e+09 title:J.T. LeRoy]
}

3.2.3 多重搜索

允许您通过将一个或多个索引捆绑到单个 HTTP 请求中来执行多个搜索查询。多重搜索也称为联合搜索。

func main() {
	// 创建 MeiliSearch 客户端实例
	client := meilisearch.NewClient(
		meilisearch.ClientConfig{
			Host:   "http://localhost:7700",
			APIKey: "3EX4QpUfpqX6XfOIks-qWg6tvpQxdWmr7CxHUN4GgaA", // 如果使用了API密钥
		},
	)

	// 多重搜索文档
	resp, err := client.MultiSearch(&meilisearch.MultiSearchRequest{
		Queries: []*meilisearch.SearchRequest{
			{
				IndexUID: "movies",
				Query:    "star",
				Limit:    2,
				Offset:   0,
			},
			{
				IndexUID: "movies",
				Query:    "\"the Fifth Element\"",
				Limit:    2,
				Offset:   0,
			},
		},
	})
	if err != nil {
		log.Fatalf("Error multi searching: %v", err)
	}

	// 输出搜索结果
	for _, movie := range resp.Results {
		fmt.Printf("%+v\n", movie)
	}
	// {Hits:[map[genres:[Adventure Action Science Fiction] id:11 overview:Princess Leia is captured and held hostage by the evil Imperial forces in their effort to take over the galactic Empire. Venturesome Luke Skywalker and dashing captain Han Solo team together with the loveable robot duo R2-D2 and C-3PO to rescue the beautiful princess and restore peace and justice in the Empire. poster:https://image.tmdb.org/t/p/w500/6FfCtAuVAW8XJjZ7eWeLibRLWTw.jpg release_date:2.333664e+08 title:Star Wars] map[genres:[Science Fiction Adventure Mystery] id:152 overview:When a destructive space entity is spotted approaching Earth, Admiral Kirk resumes command of the Starship Enterprise in order to intercept, examine, and hopefully stop it. poster:https://image.tmdb.org/t/p/w500/ffo56udrkF28ICTv3Xx1S9X6Dw4.jpg release_date:3.133728e+08 title:Star Trek: The Motion Picture]] EstimatedTotalHits:1000 Offset:0 Limit:2 ProcessingTimeMs:3 Query:star FacetDistribution:<nil> TotalHits:0 HitsPerPage:0 Page:0 TotalPages:0 FacetStats:<nil> IndexUID:movies}
	// {Hits:[map[genres:[Adventure Fantasy Action Thriller Science Fiction] id:18 overview:In 2257, a taxi driver is unintentionally given the task of saving a young girl who is part of the key that will ensure the survival of humanity. poster:https://image.tmdb.org/t/p/w500/fPtlCO1yQtnoLHOwKtWz7db6RGU.jpg release_date:8.625312e+08 title:The Fifth Element]] EstimatedTotalHits:1 Offset:0 Limit:2 ProcessingTimeMs:0 Query:"the Fifth Element" FacetDistribution:<nil> TotalHits:0 HitsPerPage:0 Page:0 TotalPages:0 FacetStats:<nil> IndexUID:movies}
}

3.2.4 相似搜索

使用人工智能驱动的搜索来返回许多与目标文档相似的文档。

func main() {
	// 创建 MeiliSearch 客户端实例
	client := meilisearch.NewClient(
		meilisearch.ClientConfig{
			Host:   "http://localhost:7700",
			APIKey: "3EX4QpUfpqX6XfOIks-qWg6tvpQxdWmr7CxHUN4GgaA", // 如果使用了API密钥
		},
	)

	// 搜索相似文档
	resp := new(meilisearch.SimilarDocumentResult)
	err := client.Index("movies").SearchSimilarDocuments(&meilisearch.SimilarDocumentQuery{
		Id: "18",
		//Embedder: "openai",
	}, resp)
	if err != nil {
		log.Fatalf("Error searching similar documents: %v", err)
	}

	fmt.Printf("Similar documents response: %+v\n", *resp)
}

3.2.5 搜索分页

我们讨论Meilisearch支持的两种不同的分页方法:一种使用offset和limit,另一种使用hitsPerPage和page。

package main

import (
	"encoding/json"
	"fmt"
	"github.com/meilisearch/meilisearch-go"
	"log"
	"os"
)

func main() {
	// 创建 MeiliSearch 客户端实例
	client := meilisearch.NewClient(
		meilisearch.ClientConfig{
			Host:   "http://localhost:7700",
			APIKey: "3EX4QpUfpqX6XfOIks-qWg6tvpQxdWmr7CxHUN4GgaA", // 如果使用了API密钥
		},
	)

	resp, err := client.Index("movies").Search("star", &meilisearch.SearchRequest{
		Page:        1,
		HitsPerPage: 5,
	})
	if err != nil {
		log.Fatalf("Error searching: %v", err)
	}
	fmt.Printf("%+v\n", resp)
	// &{Hits:[map[genres:[Adventure Action Science Fiction] id:11 overview:Princess Leia is captured and held hostage by the evil Imperial forces in their effort to take over the galactic Empire. Venturesome Luke Skywalker and dashing captain Han Solo team together with the loveable robot duo R2-D2 and C-3PO to rescue the beautiful princess and restore peace and justice in the Empire. poster:https://image.tmdb.org/t/p/w500/6FfCtAuVAW8XJjZ7eWeLibRLWTw.jpg release_date:2.333664e+08 title:Star Wars] map[genres:[Science Fiction Adventure Mystery] id:152 overview:When a destructive space entity is spotted approaching Earth, Admiral Kirk resumes command of the Starship Enterprise in order to intercept, examine, and hopefully stop it. poster:https://image.tmdb.org/t/p/w500/ffo56udrkF28ICTv3Xx1S9X6Dw4.jpg release_date:3.133728e+08 title:Star Trek: The Motion Picture] map[genres:[Action Adventure Science Fiction Thriller] id:154 overview:It is the 23rd century. The Federation Starship U.S.S. Enterprise™ is on routine training maneuvers and Admiral James T. Kirk (William Shatner) seems resigned to the fact that this inspection may well be the last space mission of his career. But Khan is back. Aided by his exiled band of genetic supermen, Khan (Ricardo Montalban) - brilliant renegade of 20th century Earth - has raided Space Station Regula One, stolen a top secret device called Project Genesis, wrested control of another Federation Starship and sets out in pursuit of the Enterprise, determined to let nothing stand in the way of his mission: kill Admiral Kirk... even if it means universal Armageddon. poster:https://image.tmdb.org/t/p/w500/uPyLsKl8Z0LOoxeaFXsY5MxhR5s.jpg release_date:3.919968e+08 title:Star Trek II: The Wrath of Khan] map[genres:[Science Fiction Action Adventure Thriller] id:157 overview:Admiral Kirk and his bridge crew risk their careers stealing the decommissioned Enterprise to return to the restricted Genesis planet to recover Spock's body. poster:https://image.tmdb.org/t/p/w500/yqEj0oPfKBMCz7YcCARHDgH7VFm.jpg release_date:4.54896e+08 title:Star Trek III: The Search for Spock] map[genres:[Science Fiction Adventure] id:168 overview:It's the 23rd century, and a mysterious alien power is threatening Earth by evaporating the oceans and destroying the atmosphere. In a frantic attempt to save mankind, Kirk and his crew must time travel back to 1986 San Francisco where they find a world of punk, pizza and exact-change buses that are as alien as anything they've ever encountered in the far reaches of the galaxy. A thrilling, action-packed Star Trek adventure! poster:https://image.tmdb.org/t/p/w500/xY5TzGXJOB3L9rhZ1MbbPyVlW5J.jpg release_date:5.333472e+08 title:Star Trek IV: The Voyage Home]] EstimatedTotalHits:0 Offset:0 Limit:0 ProcessingTimeMs:2 Query:star FacetDistribution:<nil> TotalHits:1000 HitsPerPage:5 Page:1 TotalPages:200 FacetStats:<nil> IndexUID:}
}
package main

import (
	"encoding/json"
	"fmt"
	"github.com/meilisearch/meilisearch-go"
	"log"
	"os"
)

func main() {
	// 创建 MeiliSearch 客户端实例
	client := meilisearch.NewClient(
		meilisearch.ClientConfig{
			Host:   "http://localhost:7700",
			APIKey: "3EX4QpUfpqX6XfOIks-qWg6tvpQxdWmr7CxHUN4GgaA", // 如果使用了API密钥
		},
	)

	resp, err := client.Index("movies").Search("star", &meilisearch.SearchRequest{
		Offset: 0,
		Limit:  5,
	})
	if err != nil {
		log.Fatalf("Error searching: %v", err)
	}
	fmt.Printf("%+v\n", resp)
	// &{Hits:[map[genres:[Adventure Action Science Fiction] id:11 overview:Princess Leia is captured and held hostage by the evil Imperial forces in their effort to take over the galactic Empire. Venturesome Luke Skywalker and dashing captain Han Solo team together with the loveable robot duo R2-D2 and C-3PO to rescue the beautiful princess and restore peace and justice in the Empire. poster:https://image.tmdb.org/t/p/w500/6FfCtAuVAW8XJjZ7eWeLibRLWTw.jpg release_date:2.333664e+08 title:Star Wars] map[genres:[Science Fiction Adventure Mystery] id:152 overview:When a destructive space entity is spotted approaching Earth, Admiral Kirk resumes command of the Starship Enterprise in order to intercept, examine, and hopefully stop it. poster:https://image.tmdb.org/t/p/w500/ffo56udrkF28ICTv3Xx1S9X6Dw4.jpg release_date:3.133728e+08 title:Star Trek: The Motion Picture] map[genres:[Action Adventure Science Fiction Thriller] id:154 overview:It is the 23rd century. The Federation Starship U.S.S. Enterprise™ is on routine training maneuvers and Admiral James T. Kirk (William Shatner) seems resigned to the fact that this inspection may well be the last space mission of his career. But Khan is back. Aided by his exiled band of genetic supermen, Khan (Ricardo Montalban) - brilliant renegade of 20th century Earth - has raided Space Station Regula One, stolen a top secret device called Project Genesis, wrested control of another Federation Starship and sets out in pursuit of the Enterprise, determined to let nothing stand in the way of his mission: kill Admiral Kirk... even if it means universal Armageddon. poster:https://image.tmdb.org/t/p/w500/uPyLsKl8Z0LOoxeaFXsY5MxhR5s.jpg release_date:3.919968e+08 title:Star Trek II: The Wrath of Khan] map[genres:[Science Fiction Action Adventure Thriller] id:157 overview:Admiral Kirk and his bridge crew risk their careers stealing the decommissioned Enterprise to return to the restricted Genesis planet to recover Spock's body. poster:https://image.tmdb.org/t/p/w500/yqEj0oPfKBMCz7YcCARHDgH7VFm.jpg release_date:4.54896e+08 title:Star Trek III: The Search for Spock] map[genres:[Science Fiction Adventure] id:168 overview:It's the 23rd century, and a mysterious alien power is threatening Earth by evaporating the oceans and destroying the atmosphere. In a frantic attempt to save mankind, Kirk and his crew must time travel back to 1986 San Francisco where they find a world of punk, pizza and exact-change buses that are as alien as anything they've ever encountered in the far reaches of the galaxy. A thrilling, action-packed Star Trek adventure! poster:https://image.tmdb.org/t/p/w500/xY5TzGXJOB3L9rhZ1MbbPyVlW5J.jpg release_date:5.333472e+08 title:Star Trek IV: The Voyage Home]] EstimatedTotalHits:1000 Offset:0 Limit:5 ProcessingTimeMs:3 Query:star FacetDistribution:<nil> TotalHits:0 HitsPerPage:0 Page:0 TotalPages:0 FacetStats:<nil> IndexUID:}
}

3.2.6 搜索高亮

我们讨论Meilisearch支持的两种不同的分页方法:一种使用offset和limit,另一种使用hitsPerPage和page。

package main

import (
	"encoding/json"
	"fmt"
	"github.com/meilisearch/meilisearch-go"
	"log"
	"os"
)

func main() {
	// 创建 MeiliSearch 客户端实例
	client := meilisearch.NewClient(
		meilisearch.ClientConfig{
			Host:   "http://localhost:7700",
			APIKey: "3EX4QpUfpqX6XfOIks-qWg6tvpQxdWmr7CxHUN4GgaA", // 如果使用了API密钥
		},
	)

	resp, err := client.Index("movies").Search("star", &meilisearch.SearchRequest{
		AttributesToHighlight: []string{"overview"},
		HighlightPreTag:       "<span class=\"highlight\">",
		HighlightPostTag:      "</span>",
	})
	if err != nil {
		log.Fatalf("Error searching: %v", err)
	}
	fmt.Printf("%+v\n", resp)
	// &{Hits:[map[_formatted:map[genres:[Adventure Action Science Fiction] id:11 overview:Princess Leia is captured and held hostage by the evil Imperial forces in their effort to take over the galactic Empire. Venturesome Luke Skywalker and dashing captain Han Solo team together with the loveable robot duo R2-D2 and C-3PO to rescue the beautiful princess and restore peace and justice in the Empire. poster:https://image.tmdb.org/t/p/w500/6FfCtAuVAW8XJjZ7eWeLibRLWTw.jpg release_date:233366400 title:Star Wars] genres:[Adventure Action Science Fiction] id:11 overview:Princess Leia is captured and held hostage by the evil Imperial forces in their effort to take over the galactic Empire. Venturesome Luke Skywalker and dashing captain Han Solo team together with the loveable robot duo R2-D2 and C-3PO to rescue the beautiful princess and restore peace and justice in the Empire. poster:https://image.tmdb.org/t/p/w500/6FfCtAuVAW8XJjZ7eWeLibRLWTw.jpg release_date:2.333664e+08 title:Star Wars] map[_formatted:map[genres:[Science Fiction Adventure Mystery] id:152 overview:When a destructive space entity is spotted approaching Earth, Admiral Kirk resumes command of the <span class="highlight">Star</span>ship Enterprise in order to intercept, examine, and hopefully stop it. poster:https://image.tmdb.org/t/p/w500/ffo56udrkF28ICTv3Xx1S9X6Dw4.jpg release_date:313372800 title:Star Trek: The Motion Picture] genres:[Science Fiction Adventure Mystery] id:152 overview:When a destructive space entity is spotted approaching Earth, Admiral Kirk resumes command of the Starship Enterprise in order to intercept, examine, and hopefully stop it. poster:https://image.tmdb.org/t/p/w500/ffo56udrkF28ICTv3Xx1S9X6Dw4.jpg release_date:3.133728e+08 title:Star Trek: The Motion Picture] map[_formatted:map[genres:[Action Adventure Science Fiction Thriller] id:154 overview:It is the 23rd century. The Federation <span class="highlight">Star</span>ship U.S.S. Enterprise™ is on routine training maneuvers and Admiral James T. Kirk (William Shatner) seems resigned to the fact that this inspection may well be the last space mission of his career. But Khan is back. Aided by his exiled band of genetic supermen, Khan (Ricardo Montalban) - brilliant renegade of 20th century Earth - has raided Space Station Regula One, stolen a top secret device called Project Genesis, wrested control of another Federation <span class="highlight">Star</span>ship and sets out in pursuit of the Enterprise, determined to let nothing stand in the way of his mission: kill Admiral Kirk... even if it means universal Armageddon. poster:https://image.tmdb.org/t/p/w500/uPyLsKl8Z0LOoxeaFXsY5MxhR5s.jpg release_date:391996800 title:Star Trek II: The Wrath of Khan] genres:[Action Adventure Science Fiction Thriller] id:154 overview:It is the 23rd century. The Federation Starship U.S.S. Enterprise™ is on routine training maneuvers and Admiral James T. Kirk (William Shatner) seems resigned to the fact that this inspection may well be the last space mission of his career. But Khan is back. Aided by his exiled band of genetic supermen, Khan (Ricardo Montalban) - brilliant renegade of 20th century Earth - has raided Space Station Regula One, stolen a top secret device called Project Genesis, wrested control of another Federation Starship and sets out in pursuit of the Enterprise, determined to let nothing stand in the way of his mission: kill Admiral Kirk... even if it means universal Armageddon. poster:https://image.tmdb.org/t/p/w500/uPyLsKl8Z0LOoxeaFXsY5MxhR5s.jpg release_date:3.919968e+08 title:Star Trek II: The Wrath of Khan] map[_formatted:map[genres:[Science Fiction Action Adventure Thriller] id:157 overview:Admiral Kirk and his bridge crew risk their careers stealing the decommissioned Enterprise to return to the restricted Genesis planet to recover Spock's body. poster:https://image.tmdb.org/t/p/w500/yqEj0oPfKBMCz7YcCARHDgH7VFm.jpg release_date:454896000 title:Star Trek III: The Search for Spock] genres:[Science Fiction Action Adventure Thriller] id:157 overview:Admiral Kirk and his bridge crew risk their careers stealing the decommissioned Enterprise to return to the restricted Genesis planet to recover Spock's body. poster:https://image.tmdb.org/t/p/w500/yqEj0oPfKBMCz7YcCARHDgH7VFm.jpg release_date:4.54896e+08 title:Star Trek III: The Search for Spock] map[_formatted:map[genres:[Science Fiction Adventure] id:168 overview:It's the 23rd century, and a mysterious alien power is threatening Earth by evaporating the oceans and destroying the atmosphere. In a frantic attempt to save mankind, Kirk and his crew must time travel back to 1986 San Francisco where they find a world of punk, pizza and exact-change buses that are as alien as anything they've ever encountered in the far reaches of the galaxy. A thrilling, action-packed <span class="highlight">Star</span> Trek adventure! poster:https://image.tmdb.org/t/p/w500/xY5TzGXJOB3L9rhZ1MbbPyVlW5J.jpg release_date:533347200 title:Star Trek IV: The Voyage Home] genres:[Science Fiction Adventure] id:168 overview:It's the 23rd century, and a mysterious alien power is threatening Earth by evaporating the oceans and destroying the atmosphere. In a frantic attempt to save mankind, Kirk and his crew must time travel back to 1986 San Francisco where they find a world of punk, pizza and exact-change buses that are as alien as anything they've ever encountered in the far reaches of the galaxy. A thrilling, action-packed Star Trek adventure! poster:https://image.tmdb.org/t/p/w500/xY5TzGXJOB3L9rhZ1MbbPyVlW5J.jpg release_date:5.333472e+08 title:Star Trek IV: The Voyage Home] map[_formatted:map[genres:[Science Fiction Action Adventure Thriller] id:172 overview:The crew of the Federation <span class="highlight">star</span>ship Enterprise is called to Nimbus III, the Planet of Intergalactic Peace. They are to negotiate in a case of kidnapping only to find out that the kidnapper is a relative of Spock. This man is possessed by his life long search for the planet Shaka-Ri which is supposed to be the source of all life. Together they begin to search for this mysterious planet. poster:https://image.tmdb.org/t/p/w500/uiXr41VLYsuug3CZbFrKLSNahuZ.jpg release_date:613353600 title:Star Trek V: The Final Frontier] genres:[Science Fiction Action Adventure Thriller] id:172 overview:The crew of the Federation starship Enterprise is called to Nimbus III, the Planet of Intergalactic Peace. They are to negotiate in a case of kidnapping only to find out that the kidnapper is a relative of Spock. This man is possessed by his life long search for the planet Shaka-Ri which is supposed to be the source of all life. Together they begin to search for this mysterious planet. poster:https://image.tmdb.org/t/p/w500/uiXr41VLYsuug3CZbFrKLSNahuZ.jpg release_date:6.133536e+08 title:Star Trek V: The Final Frontier] map[_formatted:map[genres:[Science Fiction Action Adventure Thriller] id:174 overview:After years of war, the Federation and the Klingon empire find themselves on the brink of a peace summit when a Klingon ship is nearly destroyed by an apparent attack from the Enterprise. Both worlds brace for what may be their dealiest encounter. poster:https://image.tmdb.org/t/p/w500/tvTOJD7Gz668GLy2nNdLRQvpPsv.jpg release_date:691977600 title:Star Trek VI: The Undiscovered Country] genres:[Science Fiction Action Adventure Thriller] id:174 overview:After years of war, the Federation and the Klingon empire find themselves on the brink of a peace summit when a Klingon ship is nearly destroyed by an apparent attack from the Enterprise. Both worlds brace for what may be their dealiest encounter. poster:https://image.tmdb.org/t/p/w500/tvTOJD7Gz668GLy2nNdLRQvpPsv.jpg release_date:6.919776e+08 title:Star Trek VI: The Undiscovered Country] map[_formatted:map[genres:[Science Fiction Action Adventure Thriller] id:193 overview:Captain Jean-Luc Picard and the crew of the Enterprise-D find themselves at odds with the renegade scientist Soran who is destroying entire <span class="highlight">star</span> systems. Only one man can help Picard stop Soran's scheme...and he's been dead for seventy-eight years. poster:https://image.tmdb.org/t/p/w500/rHsCYDGHFUarGh5k987b0EFU6kC.jpg release_date:785116800 title:Star Trek: Generations] genres:[Science Fiction Action Adventure Thriller] id:193 overview:Captain Jean-Luc Picard and the crew of the Enterprise-D find themselves at odds with the renegade scientist Soran who is destroying entire star systems. Only one man can help Picard stop Soran's scheme...and he's been dead for seventy-eight years. poster:https://image.tmdb.org/t/p/w500/rHsCYDGHFUarGh5k987b0EFU6kC.jpg release_date:7.851168e+08 title:Star Trek: Generations] map[_formatted:map[genres:[Science Fiction Action Adventure Thriller] id:199 overview:The Borg, a relentless race of cyborgs, are on a direct course for Earth. Violating orders to stay away from the battle, Captain Picard and the crew of the newly-commissioned USS Enterprise E pursue the Borg back in time to prevent the invaders from changing Federation history and assimilating the galaxy. poster:https://image.tmdb.org/t/p/w500/vrC1lkTktFQ4AqBfqf4PXoDDLcw.jpg release_date:848620800 title:Star Trek: First Contact] genres:[Science Fiction Action Adventure Thriller] id:199 overview:The Borg, a relentless race of cyborgs, are on a direct course for Earth. Violating orders to stay away from the battle, Captain Picard and the crew of the newly-commissioned USS Enterprise E pursue the Borg back in time to prevent the invaders from changing Federation history and assimilating the galaxy. poster:https://image.tmdb.org/t/p/w500/vrC1lkTktFQ4AqBfqf4PXoDDLcw.jpg release_date:8.486208e+08 title:Star Trek: First Contact] map[_formatted:map[genres:[Science Fiction Action Adventure Thriller] id:200 overview:When an alien race and factions within <span class="highlight">Star</span>fleet attempt to take over a planet that has "regenerative" properties, it falls upon Captain Picard and the crew of the Enterprise to defend the planet's people as well as the very ideals upon which the Federation itself was founded. poster:https://image.tmdb.org/t/p/w500/xQCMAHeg5M9HpDIqanYbWdr4brB.jpg release_date:913334400 title:Star Trek: Insurrection] genres:[Science Fiction Action Adventure Thriller] id:200 overview:When an alien race and factions within Starfleet attempt to take over a planet that has "regenerative" properties, it falls upon Captain Picard and the crew of the Enterprise to defend the planet's people as well as the very ideals upon which the Federation itself was founded. poster:https://image.tmdb.org/t/p/w500/xQCMAHeg5M9HpDIqanYbWdr4brB.jpg release_date:9.133344e+08 title:Star Trek: Insurrection] map[_formatted:map[genres:[Science Fiction Action Adventure Thriller] id:201 overview:En route to the honeymoon of William Riker to Deanna Troi on her home planet of Betazed, Captain Jean-Luc Picard and the crew of the U.S.S. Enterprise receives word from <span class="highlight">Star</span>fleet that a coup has resulted in the installation of a new Romulan political leader, Shinzon, who claims to seek peace with the human-backed United Federation of Planets. Once in enemy territory, the captain and his crew make a <span class="highlight">star</span>tling discovery: Shinzon is human, a slave from the Romulan sister planet of Remus, and has a secret, shocking relationship to Picard himself. poster:https://image.tmdb.org/t/p/w500/cldAwhvBmOv9jrd3bXWuqRHoXyq.jpg release_date:1039737600 title:Star Trek: Nemesis] genres:[Science Fiction Action Adventure Thriller] id:201 overview:En route to the honeymoon of William Riker to Deanna Troi on her home planet of Betazed, Captain Jean-Luc Picard and the crew of the U.S.S. Enterprise receives word from Starfleet that a coup has resulted in the installation of a new Romulan political leader, Shinzon, who claims to seek peace with the human-backed United Federation of Planets. Once in enemy territory, the captain and his crew make a startling discovery: Shinzon is human, a slave from the Romulan sister planet of Remus, and has a secret, shocking relationship to Picard himself. poster:https://image.tmdb.org/t/p/w500/cldAwhvBmOv9jrd3bXWuqRHoXyq.jpg release_date:1.0397376e+09 title:Star Trek: Nemesis] map[_formatted:map[genres:[Adventure Action Science Fiction] id:1893 overview:Anakin Skywalker, a young slave strong with the Force, is discovered on Tatooine. Meanwhile, the evil Sith have returned, enacting their plot for revenge against the Jedi. poster:https://image.tmdb.org/t/p/w500/6wkfovpn7Eq8dYNKaG5PY3q2oq6.jpg release_date:927072000 title:Star Wars: Episode I - The Phantom Menace] genres:[Adventure Action Science Fiction] id:1893 overview:Anakin Skywalker, a young slave strong with the Force, is discovered on Tatooine. Meanwhile, the evil Sith have returned, enacting their plot for revenge against the Jedi. poster:https://image.tmdb.org/t/p/w500/6wkfovpn7Eq8dYNKaG5PY3q2oq6.jpg release_date:9.27072e+08 title:Star Wars: Episode I - The Phantom Menace] map[_formatted:map[genres:[Adventure Action Science Fiction] id:1894 overview:Following an assassination attempt on Senator Padmé Amidala, Jedi Knights Anakin Skywalker and Obi-Wan Kenobi investigate a mysterious plot that could change the galaxy forever. poster:https://image.tmdb.org/t/p/w500/oZNPzxqM2s5DyVWab09NTQScDQt.jpg release_date:1021420800 title:Star Wars: Episode II - Attack of the Clones] genres:[Adventure Action Science Fiction] id:1894 overview:Following an assassination attempt on Senator Padmé Amidala, Jedi Knights Anakin Skywalker and Obi-Wan Kenobi investigate a mysterious plot that could change the galaxy forever. poster:https://image.tmdb.org/t/p/w500/oZNPzxqM2s5DyVWab09NTQScDQt.jpg release_date:1.0214208e+09 title:Star Wars: Episode II - Attack of the Clones] map[_formatted:map[genres:[Science Fiction Adventure Action] id:1895 overview:The evil Darth Sidious enacts his final plan for unlimited power -- and the heroic Jedi Anakin Skywalker must choose a side. poster:https://image.tmdb.org/t/p/w500/xfSAoBEm9MNBjmlNcDYLvLSMlnq.jpg release_date:1116288000 title:Star Wars: Episode III - Revenge of the Sith] genres:[Science Fiction Adventure Action] id:1895 overview:The evil Darth Sidious enacts his final plan for unlimited power -- and the heroic Jedi Anakin Skywalker must choose a side. poster:https://image.tmdb.org/t/p/w500/xfSAoBEm9MNBjmlNcDYLvLSMlnq.jpg release_date:1.116288e+09 title:Star Wars: Episode III - Revenge of the Sith] map[_formatted:map[genres:[Animation Action Science Fiction Adventure] id:12180 overview:Set between Episode II and III, The Clone Wars is the first computer animated <span class="highlight">Star</span> Wars film. Anakin and Obi Wan must find out who kidnapped Jabba the Hutt's son and return him safely. The Seperatists will try anything to stop them and ruin any chance of a diplomatic agreement between the Hutts and the Republic. poster:https://image.tmdb.org/t/p/w500/ywRtBu88SLAkNxD0GFib6qsFkBK.jpg release_date:1217894400 title:Star Wars: The Clone Wars] genres:[Animation Action Science Fiction Adventure] id:12180 overview:Set between Episode II and III, The Clone Wars is the first computer animated Star Wars film. Anakin and Obi Wan must find out who kidnapped Jabba the Hutt's son and return him safely. The Seperatists will try anything to stop them and ruin any chance of a diplomatic agreement between the Hutts and the Republic. poster:https://image.tmdb.org/t/p/w500/ywRtBu88SLAkNxD0GFib6qsFkBK.jpg release_date:1.2178944e+09 title:Star Wars: The Clone Wars] map[_formatted:map[genres:[Science Fiction Action Adventure] id:13475 overview:The fate of the galaxy rests in the hands of bitter rivals. One, James Kirk, is a delinquent, thrill-seeking Iowa farm boy. The other, Spock, a Vulcan, was raised in a logic-based society that rejects all emotion. As fiery instinct clashes with calm reason, their unlikely but powerful partnership is the only thing capable of leading their crew through unimaginable danger, boldly going where no one has gone before. The human adventure has begun again. poster:https://image.tmdb.org/t/p/w500/lV5OpzAss1z06YNagOVap1I35mH.jpg release_date:1241568000 title:Star Trek] genres:[Science Fiction Action Adventure] id:13475 overview:The fate of the galaxy rests in the hands of bitter rivals. One, James Kirk, is a delinquent, thrill-seeking Iowa farm boy. The other, Spock, a Vulcan, was raised in a logic-based society that rejects all emotion. As fiery instinct clashes with calm reason, their unlikely but powerful partnership is the only thing capable of leading their crew through unimaginable danger, boldly going where no one has gone before. The human adventure has begun again. poster:https://image.tmdb.org/t/p/w500/lV5OpzAss1z06YNagOVap1I35mH.jpg release_date:1.241568e+09 title:Star Trek] map[_formatted:map[genres:[Science Fiction] id:24865 overview:At the end of mankind's greatest battle, empires will crumble, alliances will form, enemies will rise and heroes will fall. World's will end, and a new journey will begin. poster:https://image.tmdb.org/t/p/w500/A68FfPRNQ526S4dh3AMOO4BYMMB.jpg release_date:1257206400 title:Star Quest: The Odyssey] genres:[Science Fiction] id:24865 overview:At the end of mankind's greatest battle, empires will crumble, alliances will form, enemies will rise and heroes will fall. World's will end, and a new journey will begin. poster:https://image.tmdb.org/t/p/w500/A68FfPRNQ526S4dh3AMOO4BYMMB.jpg release_date:1.2572064e+09 title:Star Quest: The Odyssey] map[_formatted:map[genres:[TV Movie Horror Science Fiction] id:30203 overview:Two space smuggles are caught by the government and told if they deliver a create to a certain location the charges will be forgotten. Turns out the create is the key to a cover up and other parties want it to. poster:https://image.tmdb.org/t/p/w500/bfVpoRMqaPU8u6jTmoifrVGOxX2.jpg release_date:1244851200 title:Star Runners] genres:[TV Movie Horror Science Fiction] id:30203 overview:Two space smuggles are caught by the government and told if they deliver a create to a certain location the charges will be forgotten. Turns out the create is the key to a cover up and other parties want it to. poster:https://image.tmdb.org/t/p/w500/bfVpoRMqaPU8u6jTmoifrVGOxX2.jpg release_date:1.2448512e+09 title:Star Runners] map[_formatted:map[genres:[Drama] id:30707 overview:Paul Snider is a narcissistic, small time hustler who fancies himself a ladies man. His life changes when he meets Dorothy Stratten working behind the counter of a Dairy Queen. Under his guidance Dorothy grows to fame as a Playboy Playmate. But when Dorothy begins pursuing an acting career, the jealous Paul finds himself elbowed out of the picture by more famous men. poster:https://image.tmdb.org/t/p/w500/b2SkA02fXbZYnV1qjOIQprjXloF.jpg release_date:437270400 title:Star 80] genres:[Drama] id:30707 overview:Paul Snider is a narcissistic, small time hustler who fancies himself a ladies man. His life changes when he meets Dorothy Stratten working behind the counter of a Dairy Queen. Under his guidance Dorothy grows to fame as a Playboy Playmate. But when Dorothy begins pursuing an acting career, the jealous Paul finds himself elbowed out of the picture by more famous men. poster:https://image.tmdb.org/t/p/w500/b2SkA02fXbZYnV1qjOIQprjXloF.jpg release_date:4.372704e+08 title:Star 80] map[_formatted:map[genres:[Action Comedy] id:47647 overview:<span class="highlight">Star</span> Chow (Stephen Chow) is about to be kicked out of the Royal Hong Kong Police's elite Special Duties Unit (SDU). But a senior officer decides to give him one last chance: <span class="highlight">Star</span> must go undercover as a student at the Edinburgh High School in Hong Kong to recover the senior officer's missing revolver. The undercover operation is made complicated when <span class="highlight">Star</span> is partnered with Tat - an aging, incompetent police detective (Ng Man-Tat). However, <span class="highlight">Star</span> still manages to fall in love with Ms Ho (Cheung Man), the school's guidance counselor, as well as disrupting a gang involved in arms-dealing. poster:https://image.tmdb.org/t/p/w500/wIp4g7nd7cIxRVGVoOJseeiy8yP.jpg release_date:679795200 title:Fight Back to School] genres:[Action Comedy] id:47647 overview:Star Chow (Stephen Chow) is about to be kicked out of the Royal Hong Kong Police's elite Special Duties Unit (SDU). But a senior officer decides to give him one last chance: Star must go undercover as a student at the Edinburgh High School in Hong Kong to recover the senior officer's missing revolver. The undercover operation is made complicated when Star is partnered with Tat - an aging, incompetent police detective (Ng Man-Tat). However, Star still manages to fall in love with Ms Ho (Cheung Man), the school's guidance counselor, as well as disrupting a gang involved in arms-dealing. poster:https://image.tmdb.org/t/p/w500/wIp4g7nd7cIxRVGVoOJseeiy8yP.jpg release_date:6.797952e+08 title:Fight Back to School]] EstimatedTotalHits:1000 Offset:0 Limit:20 ProcessingTimeMs:3 Query:star FacetDistribution:<nil> TotalHits:0 HitsPerPage:0 Page:0 TotalPages:0 FacetStats:<nil> IndexUID:}
}

3.2.7 同义词

如果多个单词在您的数据集中具有相同的含义,您可以 创建同义词列表。这将使您的搜索结果更加相关。

package main

import (
	"encoding/json"
	"fmt"
	"github.com/meilisearch/meilisearch-go"
	"log"
	"os"
)

func main() {
	// 创建 MeiliSearch 客户端实例
	client := meilisearch.NewClient(
		meilisearch.ClientConfig{
			Host:   "http://10.225.254.62:7700",
			APIKey: "3EX4QpUfpqX6XfOIks-qWg6tvpQxdWmr7CxHUN4GgaA", // 如果使用了API密钥
		},
	)

	// 设置同义词(请求之后等待一段时间才生效)
	//synonyms := map[string][]string{
	//	"great":     {"fantastic"},
	//	"fantastic": {"great"},
	//}
	//_, err := client.Index("movies").UpdateSynonyms(&synonyms)
	//if err != nil {
	//	return
	//}

	resp, err := client.Index("movies").Search("great", &meilisearch.SearchRequest{})
	if err != nil {
		log.Fatalf("Error searching: %v", err)
	}
	fmt.Printf("%+v\n", resp)
	// &{Hits:[map[genres:[Comedy] id:23273 overview:Oscar dreams of becoming an actor or a stuntman. To contact a manufacturer he stages an accident and consequently injures a young actress, then tries to limit the damage by taking the girl to his home. poster:https://image.tmdb.org/t/p/w500/dSLGHuYPDMAoVebdl7OPPDXfqfO.jpg release_date:5.074272e+08 title:Great!] map[genres:[Comedy Drama Romance] id:9410 overview:Loosely based on the Charles Dickens' classic novel, "Great Expectations" is a sensual tale of a young man's unforgettable passage into manhood, and the three individuals who will undeniably change his life forever. Through the surprising interactions of these vivid characters, "Great Expectations" takes a unique and contemporary look at life's great coincidences. poster:https://image.tmdb.org/t/p/w500/gaYBDBEldgpTwWIXaqt9HlB4YH0.jpg release_date:8.85168e+08 title:Great Expectations] map[genres:[Drama History Music] id:11465 overview:The story of Jerry Lee Lewis, arguably the greatest and certainly one of the wildest musicians of the 1950s. His arrogance, remarkable talent, and unconventional lifestyle often brought him into conflict with others in the industry, and even earned him the scorn and condemnation of the public. poster:https://image.tmdb.org/t/p/w500/cb0zpDUnHBj8PxWQG5L96m3rxrk.jpg release_date:6.15168e+08 title:Great Balls of Fire!] map[genres:[Romance Drama] id:14320 overview:In this Dickens adaptation, orphan Pip discovers through lawyer Mr. Jaggers that a mysterious benefactor wishes to ensure that he becomes a gentleman. Reunited with his childhood patron, Miss Havisham, and his first love, the beautiful but emotionally cold Estella, he discovers that the elderly spinster has gone mad from having been left at the altar as a young woman, and has made her charge into a warped, unfeeling heartbreaker. poster:https://image.tmdb.org/t/p/w500/ynaFuVvW2jaG06pMV67dOhzMYfJ.jpg release_date:-7.263648e+08 title:Great Expectations] map[genres:[Drama Romance] id:16075 overview:A young boy called Pip stumbles upon a hunted criminal who threatens him and demands food. A few years later, Pip finds that he has a benefactor. Imagining that Miss Havisham, a rich lady whose adopted daughter Estella he loves, is the benefactor, Pip believes in a grand plan at the end of which he will be married to Estella. However, when the criminal from his childhood turns up one stormy night and reveals that he, Magwitch, is his benefactor, Pip finds his dreams crumbling. Although initially repulsed by his benefactor, Pip gradually becomes loyal to him and stays with him until his death. poster:https://image.tmdb.org/t/p/w500/7P5f1YXS6xzndpjFV7gOi17U34e.jpg release_date:9.238752e+08 title:Great Expectations] map[genres:[Comedy Drama Music] id:25919 overview:When a man answers an ad to train as a record producer, he's excited by the prospect of signing undiscovered artists only to discover his new job isn't all it's cracked up to be. poster:https://image.tmdb.org/t/p/w500/6p4FlQ89dLNLKOvRAeWkvb2Pv9n.jpg release_date:1.1692512e+09 title:Great World of Sound] map[genres:[Animation Action Adventure Science Fiction] id:74621 overview:When an UFO delivers a metal-eating monster to the heart of Japan, Getter Robo and Mazinger Z are launched to combat the alien menace. Fighting individually, the space monster's metal-eating and acid-spitting abilities prove too much for Japan's super robot forces - only their combined might stands a chance against defeating it! But with Mazinger Z damaged, can Getter Robo defend against the monster long enough for its comrade to be repaired? And even with forces combined, can they defeat the monster before all of Japan is destroyed? poster:https://image.tmdb.org/t/p/w500/89YVgEo3wo3PGpVKgiPwzThmqAD.jpg release_date:1.672704e+08 title:Great Mazinger vs. Getter Robo] map[genres:[Drama Romance] id:121674 overview:Miss Havisham, a wealthy spinster who wears an old wedding dress and lives in the dilapidated Satis House, asks Pip's 'Uncle Pumblechook' to find a boy to play with her adopted daughter Estella. Pip begins to visit Miss Havisham and Estella, with whom he falls in love, then Pip—a humble orphan—suddenly becomes a gentleman with the help of an unknown benefactor. poster:https://image.tmdb.org/t/p/w500/3Iy2cfqlhAjW41apXYzNrZEkgn1.jpg release_date:1.3542336e+09 title:Great Expectations] map[genres:[Documentary] id:175373 overview:David Attenborough sets out on a journey across the seven continents in search of the most impressive and inspiring natural wonders of our planet. poster:https://image.tmdb.org/t/p/w500/5NvgXzyVNLN8olYSmjB5T7X5f37.jpg release_date:1.0098432e+09 title:Great Natural Wonders of the World] map[genres:[Drama] id:182514 overview:This stunning adaptation of Dickens' classic tale was captured live from the Vaudeville Theatre in the West End. Although Great Expectations has been adapted for film on two separate occasions, once by David Lean in 1946 and most recently by Mike Newell, it has never been produced for The West End or Broadway, widely believed to be too difficult to translate to stage. However, this Jo Clifford adaptation has been universally acclaimed as a triumph on its sellout tour of the UK head of its West End debut. In addition to the production, this version include red carpet arrivals from the February 7 premiere and behind the scenes footage exclusively for cinema audiences. poster:https://image.tmdb.org/t/p/w500/9s4tFVSWOaSa23rFJ9nsaojLqOr.jpg release_date:1.3649472e+09 title:Great Expectations] map[genres:[Horror Comedy] id:257450 overview:Great white sharks bio-engineered to be the size of piranhas with the purpose of living in rich peoples exotic aquariums, terrorize New York City when they get into the water supply and do what great white sharks do best. poster:https://image.tmdb.org/t/p/w500/v60laZMOAaifzlGN38bDAXYgqI2.jpg release_date:1.3995072e+09 title:Piranha Sharks] map[genres:[Documentary] id:273989 overview:Great Smoky Mountain National Park covers over 500,000 acres of breath-taking beauty: lush highland meadows, glorious waterfalls, pristine mountain streams, and one of the most biologically diverse ecosystems in the world. poster:https://image.tmdb.org/t/p/w500/iUZHG8q9sF1RXWhMbAA14KhS8dh.jpg release_date:1.3226976e+09 title:National Parks Exploration Series: Great Smoky Mountains] map[genres:[Documentary] id:384525 overview:It is the world's largest coral reef, the largest living structure on the planet and one of the wonders of the natural world. The three episodes of this documentary series explore in depth this biological miracle located in the Coral Sea in northeastern Australia and its complex life along more than 2,000 kilometers long. A journey from Heron Island in the south to the remote Torres Strait in the north. From the depths beyond the reef to the coral gardens and forests on the shores. poster:https://image.tmdb.org/t/p/w500/sISbmg6EJYFwutDnuGq9N3eCeDT.jpg release_date:1.325376e+09 title:Great Barrier Reef] map[genres:[Drama] id:398111 overview:Inspired by True Events An abused wife and mother to a young boy escapes her violent husband and heads for California with her son. She soon learns that her husband has accused her of kidnapping and the law is in hot pursuit. Now a fugitive, she must risk her life and freedom to protect them both from this predator of a man. poster:https://image.tmdb.org/t/p/w500/de6YWLMYZ7OPqCuUzQEpFDIekKx.jpg release_date:1.4690592e+09 title:Great Plains] map[genres:[Adventure Fantasy Action Thriller] id:1979 overview:The Fantastic Four return to the big screen as a new and all powerful enemy threatens the Earth. The seemingly unstoppable 'Silver Surfer', but all is not what it seems and there are old and new enemies that pose a greater threat than the intrepid superheroes realize. poster:https://image.tmdb.org/t/p/w500/9wRfzTcMyyzkQxVDqBHv8RwuZOv.jpg release_date:1.1816928e+09 title:Fantastic Four: Rise of the Silver Surfer] map[genres:[Adventure Science Fiction] id:2161 overview:In order to save an assassinated scientist, a submarine and its crew are shrunk to microscopic size and injected into his bloodstream. poster:https://image.tmdb.org/t/p/w500/dbwr0hGmJs2Rwh5zXbYEGBFVYTt.jpg release_date:-1.059264e+08 title:Fantastic Voyage] map[genres:[Action Adventure Fantasy Science Fiction] id:9738 overview:During a space voyage, four scientists are altered by cosmic rays: Reed Richards gains the ability to stretch his body; Sue Storm can become invisible; Johnny Storm controls fire; and Ben Grimm is turned into a super-strong … thing. Together, these "Fantastic Four" must now thwart the evil plans of Dr. Doom and save the world from certain destruction. poster:https://image.tmdb.org/t/p/w500/8HLQLILZLhDQWO6JDpvY6XJLH75.jpg release_date:1.1200032e+09 title:Fantastic Four] map[genres:[Adventure Animation Comedy Family] id:10315 overview:The Fantastic Mr. Fox bored with his current life, plans a heist against the three local farmers. The farmers, tired of sharing their chickens with the sly fox, seek revenge against him and his family. poster:https://image.tmdb.org/t/p/w500/njbTizADSZg4PqeyJdDzZGooikv.jpg release_date:1.256256e+09 title:Fantastic Mr. Fox] map[genres:[Animation Science Fiction] id:16306 overview:On the planet Ygam, the Draags, extremely technologically and spiritually advanced blue humanoids, consider the tiny Oms, human beings descendants of Terra's inhabitants, as ignorant animals. Those who live in slavery are treated as simple pets and used to entertain Draag children; those who live hidden in the hostile wilderness of the planet are periodically hunted and ruthlessly slaughtered as if they were vermin. poster:https://image.tmdb.org/t/p/w500/prq0j1S0K07UjwLZLF6oMGflRUI.jpg release_date:1.23552e+08 title:Fantastic Planet] map[genres:[Comedy Drama] id:142158 overview:When Gabino's father returns home after a long absence, the two men awkwardly attempt to re-establish a relationship; but Gabino and his mother quickly tire of this man who has become a stranger to them and decide to kick him out, before realizing that he has already left. Gabino eventually tracks his father down and spends time with him in his rundown apartment, trying to figure out if there is any possibility for the two of them to ever truly communicate. Though Greatest Hits continues Pereda's exploration of his perennial themes of absence, masculinity and the difficulty of maintaining a family, it opens up a whole new set of aesthetic questions through a bold formal gambit: halfway through, the entire narrative reboots and starts from scratch with another actor playing one of the key characters, leading to different iterations of events already witnessed. poster:https://image.tmdb.org/t/p/w500/syW6D3G5HtnMjzycFn5SjQFqai4.jpg release_date:1.3438656e+09 title:Greatest Hits]] EstimatedTotalHits:1000 Offset:0 Limit:20 ProcessingTimeMs:1 Query:great FacetDistribution:<nil> TotalHits:0 HitsPerPage:0 Page:0 TotalPages:0 FacetStats:<nil> IndexUID:}
}

3.2.8  停用词

定义一组词汇,这些词汇在进行搜索时会被忽略。停用词通常包括常见的功能词,如冠词、介词、连词等,它们对于理解文本的意义贡献不大,但在文本中却频繁出现,可能会干扰搜索结果的相关性评分。

package main

import (
	"encoding/json"
	"fmt"
	"github.com/meilisearch/meilisearch-go"
	"log"
	"os"
)

func main() {
	// 创建 MeiliSearch 客户端实例
	client := meilisearch.NewClient(
		meilisearch.ClientConfig{
			Host:   "http://localhost:7700",
			APIKey: "3EX4QpUfpqX6XfOIks-qWg6tvpQxdWmr7CxHUN4GgaA", // 如果使用了API密钥
		},
	)

	// 设置停用词(请求之后等待一段时间才生效)
	stopWords := []string{"the", "and", "is", "in", "it", "to", "of", "that", "a", "an"}
	_, err := client.Index("movies").UpdateStopWords(&stopWords)
	if err != nil {
		log.Fatalf("Error updating stop words: %v", err)
	}

	resp, err := client.Index("movies").Search("the", &meilisearch.SearchRequest{})
	if err != nil {
		log.Fatalf("Error searching: %v", err)
	}
	fmt.Printf("%+v\n", resp)
	// &{Hits:[map[genres:[Horror Thriller Mystery] id:17 overview:Adèle and her daughter Sarah are traveling on the Welsh coastline to see her husband James when Sarah disappears. A different but similar looking girl appears who says she died in a past time. Adèle tries to discover what happened to her daughter as she is tormented by Celtic mythology from the past. poster:https://image.tmdb.org/t/p/w500/wZeBHVnCvaS2bwkb8jFQ0PwZwXq.jpg release_date:1.1278656e+09 title:The Dark] map[genres:[Adventure Fantasy Action Thriller Science Fiction] id:18 overview:In 2257, a taxi driver is unintentionally given the task of saving a young girl who is part of the key that will ensure the survival of humanity. poster:https://image.tmdb.org/t/p/w500/fPtlCO1yQtnoLHOwKtWz7db6RGU.jpg release_date:8.625312e+08 title:The Fifth Element] map[genres:[Documentary] id:21 overview:Bruce Brown's The Endless Summer is one of the first and most influential surf movies of all time. The film documents American surfers Mike Hynson and Robert August as they travel the world during California’s winter (which, back in 1965 was off-season for surfing) in search of the perfect wave and ultimately, an endless summer. poster:https://image.tmdb.org/t/p/w500/5W5uaqQ7NZTwoDMKO4AtdcahHex.jpg release_date:-1.119744e+08 title:The Endless Summer] map[genres:[Animation Comedy Family] id:35 overview:After Homer accidentally pollutes the town's water supply, Springfield is encased in a gigantic dome by the EPA and the Simpsons are declared fugitives. poster:https://image.tmdb.org/t/p/w500/s3b8TZWwmkYc2KoJ5zk77qB6PzY.jpg release_date:1.1853216e+09 title:The Simpsons Movie] map[genres:[Music Drama] id:65 overview:The setting is Detroit in 1995. The city is divided by 8 Mile, a road that splits the town in half along racial lines. A young white rapper, Jimmy "B-Rabbit" Smith Jr. summons strength within himself to cross over these arbitrary boundaries to fulfill his dream of success in hip hop. With his pal Future and the three one third in place, all he has to do is not choke. poster:https://image.tmdb.org/t/p/w500/7BmQj8qE1FLuLTf7Xjf9sdIHzoa.jpg release_date:1.0367136e+09 title:8 Mile] map[genres:[Drama Romance] id:86 overview:Based on Michel Houellebecq's controversial novel, Atomised (aka The Elementary Particles) focuses on Michael and Bruno, two very different half-brothers and their disturbed sexuality.  After a chaotic childhood with a hippie mother only caring for her affairs, Michael, a molecular biologist, is more interested in genes than women, while Bruno is obsessed with his sexual desires, but mostly finds his satisfaction with prostitutes.  But Bruno's life changes when he gets to know the experienced Christiane.  In the meantime, Michael meets Annabelle, the love of his youth, again. poster:https://image.tmdb.org/t/p/w500/wpGpR7GewyApPgqPvuWadBAfmFc.jpg release_date:1.1395296e+09 title:The Elementary Particles] map[genres:[Action Comedy Crime] id:90 overview:The heat is on in this fast paced action-comedy starring Eddie Murphy as Axel Foley, a street smart Detroit cop tracking down his best friend's killer in Beverly Hills. Axel quickly learns that his wild style doesn't fit in with the Beverly Hills Police Department, which assigns two officers (Judge Reinhold & John Ashton) to make sure things don't get out of hand. Dragging the stuffy detectives along for the ride, Axel smashes through a huge culture clash in his hilarious, high-speed pursuit of justice. Featuring cameos by Paul Reiser, Bronson Pinchot and Damon Wayans, Beverly Hills Cop is an exhilarating, sidesplitting adventure. poster:https://image.tmdb.org/t/p/w500/cCSqo23BEHDcnx7xgFyFqjBykOj.jpg release_date:4.706208e+08 title:Beverly Hills Cop] map[genres:[Comedy Crime] id:115 overview:Jeffrey 'The Dude' Lebowski, a Los Angeles slacker who only wants to bowl and drink White Russians, is mistaken for another Jeffrey Lebowski, a wheelchair-bound millionaire, and finds himself dragged into a strange series of events involving nihilists, adult film producers, ferrets, errant toes, and large sums of money. poster:https://image.tmdb.org/t/p/w500/d4J7GotCjvDJBAYayZBTc5nLbbP.jpg release_date:8.891424e+08 title:The Big Lebowski] map[genres:[Crime Drama History Thriller] id:117 overview:Young Treasury Agent Elliot Ness arrives in Chicago and is determined to take down Al Capone, but it's not going to be easy because Capone has the police in his pocket. Ness meets Jimmy Malone, a veteran patrolman and probably the most honorable one on the force. He asks Malone to help him get Capone, but Malone warns him that if he goes after Capone, he is going to war. poster:https://image.tmdb.org/t/p/w500/iK4twY48a1nVCez0qXE5w4JFvXw.jpg release_date:5.496768e+08 title:The Untouchables] map[genres:[Adventure Fantasy Action] id:120 overview:Young hobbit Frodo Baggins, after inheriting a mysterious ring from his uncle Bilbo, must leave his home in order to keep it from falling into the hands of its evil creator. Along the way, a fellowship is formed to protect the ringbearer and make sure that the ring arrives at its final destination: Mt. Doom, the only place where it can be destroyed. poster:https://image.tmdb.org/t/p/w500/6oom5QYQ2yQTMJIbnvbkBL9cHo6.jpg release_date:1.0086336e+09 title:The Lord of the Rings: The Fellowship of the Ring] map[genres:[Adventure Fantasy Action] id:121 overview:Frodo and Sam are trekking to Mordor to destroy the One Ring of Power while Gimli, Legolas and Aragorn search for the orc-captured Merry and Pippin. All along, nefarious wizard Saruman awaits the Fellowship members at the Orthanc Tower in Isengard. poster:https://image.tmdb.org/t/p/w500/5VTN0pR8gcqV3EPUHHfMGnJYN9L.jpg release_date:1.0401696e+09 title:The Lord of the Rings: The Two Towers] map[genres:[Adventure Fantasy Action] id:122 overview:Aragorn is revealed as the heir to the ancient kings as he, Gandalf and the other members of the broken fellowship struggle to save Gondor from Sauron's forces. Meanwhile, Frodo and Sam take the ring closer to the heart of Mordor, the dark lord's realm. poster:https://image.tmdb.org/t/p/w500/rCzpDGLbOoPwLjy3OAm5NUPOTrC.jpg release_date:1.0702368e+09 title:The Lord of the Rings: The Return of the King] map[genres:[Adventure Animation Fantasy] id:123 overview:The Fellowship of the Ring embark on a journey to destroy the One Ring and end Sauron's reign over Middle-earth. poster:https://image.tmdb.org/t/p/w500/4O3s0IGZJirPBecqEnP9qsjlTQw.jpg release_date:2.79936e+08 title:The Lord of the Rings] map[genres:[Documentary Music] id:132 overview:The landmark documentary about the tragically ill-fated Rolling Stones free concert at Altamont Speedway on December 6, 1969. Only four months earlier, Woodstock defined the Love Generation; now it lay in ruins on a desolate racetrack six miles outside of San Francisco. poster:https://image.tmdb.org/t/p/w500/9cQ6TLG89Yv2EMKuxgLRvgLq5nK.jpg release_date:2.92896e+07 title:Gimme Shelter] map[genres:[Drama] id:147 overview:For young Parisian boy Antoine Doinel, life is one difficult situation after another. Surrounded by inconsiderate adults, including his neglectful parents, Antoine spends his days with his best friend, Rene, trying to plan for a better life. When one of their schemes goes awry, Antoine ends up in trouble with the law, leading to even more conflicts with unsympathetic authority figures. poster:https://image.tmdb.org/t/p/w500/12PuU23kkDLvTd0nb8hMlE3oShB.jpg release_date:-3.33936e+08 title:The 400 Blows] map[genres:[Drama Romance] id:148 overview:A touching story of a deaf girl who is sent to an oil rig to take care of a man who has been blinded in a terrible accident. The girl has a special ability to communicate with the men on board and especially with her patient as they share intimate moments together that will change their lives forever. poster:https://image.tmdb.org/t/p/w500/5V7i63rodY56cGWmPATxumzj4xv.jpg release_date:1.1346048e+09 title:The Secret Life of Words] map[genres:[Drama Action Crime Thriller] id:155 overview:Batman raises the stakes in his war on crime. With the help of Lt. Jim Gordon and District Attorney Harvey Dent, Batman sets out to dismantle the remaining criminal organizations that plague the streets. The partnership proves to be effective, but they soon find themselves prey to a reign of chaos unleashed by a rising criminal mastermind known to the terrified citizens of Gotham as the Joker. poster:https://image.tmdb.org/t/p/w500/qJ2tW6WMUDux911r6m7haRef0WH.jpg release_date:1.2161664e+09 title:The Dark Knight] map[genres:[Comedy Drama Romance] id:164 overview:The names Audrey Hepburn and Holly Golightly have become synonymous since this dazzling romantic comedy was translated to the screen from Truman Capote’s best-selling novella. Holly is a deliciously eccentric New York City playgirl determined to marry a Brazilian millionaire. George Peppard plays her next-door neighbour, a writer who is “sponsored” by a wealthy Patricia Neal. Guessing who’s the right man for Holly is easy. Seeing just how that romance blossoms is one of the enduring delights of this gem-like treat set to Henry Mancini’s Oscar®-winning score and the Oscar®-winning Mancini-Johnny Mercer song “Moon River.” poster:https://image.tmdb.org/t/p/w500/h3GDLoBUTiVFm4UMrok5tibFwqC.jpg release_date:-2.599776e+08 title:Breakfast at Tiffany's] map[genres:[Drama Romance Comedy Family] id:166 overview:A thirteen-year-old French girl deals with moving to a new city and school in Paris, while at the same time her parents are getting a divorce. poster:https://image.tmdb.org/t/p/w500/qxIbrx8xQuRAoceifhKhAldi5k9.jpg release_date:3.458592e+08 title:The Party] map[genres:[Comedy Romance Drama] id:171 overview:A young French teenage girl after moving to a new city falls in love with a boy and is thinking of having sex with him because her girlfriends have already done it. poster:https://image.tmdb.org/t/p/w500/x2oI5CA7lzGwY9NzZCCmZXzFBz7.jpg release_date:4.081536e+08 title:The Party 2]] EstimatedTotalHits:1000 Offset:0 Limit:20 ProcessingTimeMs:3 Query:the FacetDistribution:<nil> TotalHits:0 HitsPerPage:0 Page:0 TotalPages:0 FacetStats:<nil> IndexUID:}
}

结论

通过本文,我们深入了解了 MeiliSearch 的核心特性和优势,并通过 Go 语言示例展示了如何有效地利用 MeiliSearch 构建出色的搜索体验。无论是在开发阶段还是生产环境中,合理运用 MeiliSearch 可以显著提升应用程序的用户体验。希望本文能帮助您更好地理解和使用 MeiliSearch,如果您有任何疑问或需要更多帮助,请随时联系我。

  • 15
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值