使用正则表达式在过滤器中返回多个值

发布于 2025-01-09 18:22:25 字数 3001 浏览 0 评论 0原文

我有一个 JSON 文件,每条记录都遵循这样的格式,其中包含世界各地各个城市的名称。

{
    "_id": {
        "$oid": "5f856f2ee2d00c1818791982"
    },
    "name": "Sant Julia de Loria",
    "all_names": "Sant Julià de Lòria, Sant Julia de Loria, San Julia,San Julià,Sant Julia de Loria,Sant Julià de Lòria,Sant-Zhulija-de-Lorija,sheng hu li ya-de luo li ya,Сант-Жулия-де-Лория,サン・ジュリア・デ・ロリア教区,圣胡利娅-德洛里亚,圣胡利娅-德洛里亚",
    "alternate_names": "San Julia,San Julià,Sant Julia de Loria,Sant Julià de Lòria,Sant-Zhulija-de-Lorija,sheng hu li ya-de luo li ya,Сант-Жулия-де-Лория,サン・ジュリア・デ・ロリア教区,圣胡利娅-德洛里亚,圣胡利娅-德洛里亚",
    "country_code": "AD",
    "country_name": "Andorra"
}

我的应用程序在通过 URL 参数查询时基本上会返回城市名称。这应该通过正则表达式过滤器,然后在 JSON 中搜索适当的城市名称。

func searchCity(w http.ResponseWriter, r *http.Request) { // GET request that takes in a url param and returns a list of cities from the DB
    w.Header().Set("Content-Type", "application/json")

    values := r.URL.Query()
    city := values["city_name"]                                                               // Assigns url param from route `/suggest?city_name=` to 'city'
    cityCollection := client.Database(os.Getenv("CITY_DB")).Collection(os.Getenv("COL_CITY")) // Holds 'city' collection from DB

    if len(city) == 0 {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte(`{"Error": "City name cannot be empty!"}`))
        return
    }

    filter := bson.D{ //Regex filter for querying the input through the DB
        primitive.E{
            Key: "all_names", Value: primitive.Regex{
                Pattern: city[0], Options: "i",
            },
        },
    }

    cursor, err := cityCollection.Find(r.Context(), filter) // Query to find city is declared with cursor
    if err != nil {
        log.Fatal(err)
        w.WriteHeader(http.StatusInternalServerError)
        w.Write([]byte(`{"Error": "Could not execute cursor into query."}`))
        return
    }

    var cityList []City
    for cursor.Next(context.TODO()) { // Runs through each document entry in DB to see if regex matches
        var cities City
        err := cursor.Decode(&cities)
        if err != nil {
            log.Fatal(err)
            w.WriteHeader(http.StatusInternalServerError)
            w.Write([]byte(`{"Error": "Could not run cursor."}`))
            return
        }
        cityList = append(cityList, cities) // List of cities is appended to cityList
    }
    w.WriteHeader(http.StatusOK)
    if len(cityList) == 0 {
        w.Write([]byte(`{"cities": []}`))
        return
    }
    json.NewEncoder(w).Encode(cityList)

}

用于创建 cityList 对象的 City 类型模型包含正确的值。

type City struct {
    Name    string `bson:"name" json:"name"`
    Country string `bson:"country" json:"country"`
}

我一直在尝试返回 country_name 以及城市名称,但我不知道如何将其正确写入过滤器。

I have a JSON file that follows a format like this for each record containing the names of various cities across the world.

{
    "_id": {
        "$oid": "5f856f2ee2d00c1818791982"
    },
    "name": "Sant Julia de Loria",
    "all_names": "Sant Julià de Lòria, Sant Julia de Loria, San Julia,San Julià,Sant Julia de Loria,Sant Julià de Lòria,Sant-Zhulija-de-Lorija,sheng hu li ya-de luo li ya,Сант-Жулия-де-Лория,サン・ジュリア・デ・ロリア教区,圣胡利娅-德洛里亚,圣胡利娅-德洛里亚",
    "alternate_names": "San Julia,San Julià,Sant Julia de Loria,Sant Julià de Lòria,Sant-Zhulija-de-Lorija,sheng hu li ya-de luo li ya,Сант-Жулия-де-Лория,サン・ジュリア・デ・ロリア教区,圣胡利娅-德洛里亚,圣胡利娅-德洛里亚",
    "country_code": "AD",
    "country_name": "Andorra"
}

My app basically returns the name of the city when querying it through a URL parameter. This is supposed to pass through a regex filter and then searches the JSON for the appropriate city name.

func searchCity(w http.ResponseWriter, r *http.Request) { // GET request that takes in a url param and returns a list of cities from the DB
    w.Header().Set("Content-Type", "application/json")

    values := r.URL.Query()
    city := values["city_name"]                                                               // Assigns url param from route `/suggest?city_name=` to 'city'
    cityCollection := client.Database(os.Getenv("CITY_DB")).Collection(os.Getenv("COL_CITY")) // Holds 'city' collection from DB

    if len(city) == 0 {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte(`{"Error": "City name cannot be empty!"}`))
        return
    }

    filter := bson.D{ //Regex filter for querying the input through the DB
        primitive.E{
            Key: "all_names", Value: primitive.Regex{
                Pattern: city[0], Options: "i",
            },
        },
    }

    cursor, err := cityCollection.Find(r.Context(), filter) // Query to find city is declared with cursor
    if err != nil {
        log.Fatal(err)
        w.WriteHeader(http.StatusInternalServerError)
        w.Write([]byte(`{"Error": "Could not execute cursor into query."}`))
        return
    }

    var cityList []City
    for cursor.Next(context.TODO()) { // Runs through each document entry in DB to see if regex matches
        var cities City
        err := cursor.Decode(&cities)
        if err != nil {
            log.Fatal(err)
            w.WriteHeader(http.StatusInternalServerError)
            w.Write([]byte(`{"Error": "Could not run cursor."}`))
            return
        }
        cityList = append(cityList, cities) // List of cities is appended to cityList
    }
    w.WriteHeader(http.StatusOK)
    if len(cityList) == 0 {
        w.Write([]byte(`{"cities": []}`))
        return
    }
    json.NewEncoder(w).Encode(cityList)

}

The City type model that's used to create the cityList object holds the correct values.

type City struct {
    Name    string `bson:"name" json:"name"`
    Country string `bson:"country" json:"country"`
}

I've been trying to return the country_name along with the city name but I can't figure how to write it into the filter properly.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文