美文网首页
使用Meilisearch替代ElasticSearch

使用Meilisearch替代ElasticSearch

作者: LazyGunner | 来源:发表于2023-04-11 21:38 被阅读0次

    自己服务器缩减开支,降配到2G内存,之前跑的ES实在是不够用。挣扎了很久终于,决定用Meilisearch来替换ElasticSearch。让我没想到的是,整个替换过程非常的顺畅,两个项目满打满算不到一天就切换完了。接下来简单介绍一下过程。欢迎搜索GunnerTalk关注我

    一切的一切都是基于官方文档,https://docs.meilisearch.com/learn/getting_started/quick_start.html#setup-and-installation

    安装

    # 安装 Meilisearch
    curl -L https://install.meilisearch.com | sh
    
    ### 启动 Meilisearch
    ./meilisearch</pre>
    
    image.png

    但是当我运行的时候报错了,报错信息是 version **GLIBC_2.27**not found

    image.png

    后面我还尝试的自己去build了glib,但是无奈我的服务器是centos7,有点老了,最终还是选择放弃,选择用docker来安装和运行

    使用docker 安装 & 运行

    docker pull getmeili/meilisearch:v1.1
    
    docker run -it --rm \
      -p 7700:7700 \
      -e MEILI_MASTER_KEY='your_master_key'\
      -v $(pwd)/meili_data:/meili_data \
      getmeili/meilisearch:v1.1
    

    记得把 MEILI_MASTER_KEY 替换成自己的 key,并不要泄露。

    启动成功后,通过服务器地址:7700端口,可以访问web界面

    image.png

    接下来我们要做两件事情:

    1. 讲数据库中的数据导入到meilisearch的index中
    2. 重写搜索方法,我的项目是用Go写的,所以这里的搜索实践是用的Go

    1. 用Python写导入脚本

    # Connect to MeiliSearch
    meili_client = meilisearch.Client("http://test.com:7700", "test")
    
    # tasks = meili_client.get_tasks()
    # import pdb; pdb.set_trace()
    
    results = meili_client.index('resources').get_documents({'limit':2})
    print(results.results)
    
    # Create an index in MeiliSearch
    # index = meili_client.create_index("resources")
    
    # Fetch and import data in batches of 1000 rows
    batch_size = 100
    num_batches = (total_rows + batch_size - 1) // batch_size
    
    for i in range(num_batches):
        offset = i * batch_size
        sql = f"SELECT * FROM `resource` LIMIT {batch_size} OFFSET {offset};"
        cursor.execute(sql)
        data = cursor.fetchall()
    
        # Prepare the data for MeiliSearch
        documents = []
        for row in data:
            document = {
                # "id": row["id"],
                "resource_id": row["resource_id"],
                "cn_name": row["cn_name"],
                "en_name": row["en_name"],
            }
            documents.append(document)
    
        # Add the documents to the index
        rsp = meili_client.index('resources').add_documents(documents)
        print(rsp)
    
        # Display progress
        print(f"Imported batch {i + 1} of {num_batches}")
    
    print("Documents imported to MeiliSearch successfully!")
    

    2. 用Go来写搜索方法

    更新原开发环境

    因为项目很久没有更新了,现更新一下go的版本

    go mod edit -go 1.19
    
    go get github.com/gomodule/redigo@latest
    

    安装go-sdk

    go get github.com/meilisearch/meilisearch-go
    

    后报错 missing go.sum entry for module providing package ,通过一下命令解决

    go mod tidy
    

    Go-搜索方法

    func (r *ResourceNewController) SearchResourceMeili() {
        query := r.GetString("query")
        page, _ := strconv.Atoi(r.GetString("page"))
    
        client := meilisearch.NewClient(meilisearch.ClientConfig{
            Host:   "http://test.com:7700",
            APIKey: "test",
        })
    
        resp, err := client.Index("resources").Search(query, &meilisearch.SearchRequest{
            Limit:  10,
            Offset: int64(page - 1),
        })
        if err != nil {
            panic(err)
        }
    
        r.Result.Data = resp.Hits
        r.ServeJSON()
    }
    

    条件筛选

    添加筛选条件字段

    如果不添加会有报错

    Handler crashed with error unaccepted status code found: 400 expected: [200], MeilisearchApiError Message: Attribute `brand_id` is not filterable. This index does not have configured filterable attributes.

    添加筛选字段的方法

    meili_client.index('resources').update_filterable_attributes(['brand_id', 'category_id'])

    使用筛选的方法
    searchRequest := &meilisearch.SearchRequest{
            Limit:  int64(num),
            Offset: int64(page - 1),
        }
        filterStr := ""
        if category_id != 0 {
            filterStr = "category_id = " + strconv.Itoa(category_id)
        }
        if brand_id != 0 {
            if filterStr != "" {
                filterStr += " AND "
            }
            filterStr += "brand_id = " + strconv.Itoa(brand_id)
        }
        fmt.Println(filterStr)
        if filterStr != "" {
            searchRequest.Filter = filterStr
        }
    
        resp, err := client.Index("dune_items").Search(query, searchRequest)
        if err != nil {
            panic(err)
        }
    

    通过searchRequest中的Filter参数来进行筛选。

    非常简单的完成了ElasticSearch到MeiliSearch的迁移,这个过程中也在让我思考,传统搜索引擎和目前AI带来的搜索的变革是怎样一种对抗或者结合。最近也在学习向量数据库和Embedding相关知识,争取近期写一些文章出来。

    相关文章

      网友评论

          本文标题:使用Meilisearch替代ElasticSearch

          本文链接:https://www.haomeiwen.com/subject/yfhnddtx.html