【问题标题】:Search the record based on struct values in golang根据golang中的结构值搜索记录
【发布时间】:2018-06-15 21:29:04
【问题描述】:

我正在为搜索功能编写服务。当我在正文中传递值以获取特定记录时,我只能根据 PHONE 的结构值获取它。

我对 golang 很陌生。

我需要使用结构中的所有字段来搜索 ex.phone 或患者结构的名字或姓氏的值

我的结构如下

type PatientEntity struct {
    ID        int64 
    FirstName string 
    LastName  string 
    Phone     string 
}

我的代码是

func SearchPatientsHandler(res http.ResponseWriter, req *http.Request) {
    patient := &PatientEntity{}
    if err := json.NewDecoder(req.Body).Decode(patient); err != nil {
        panic(err)
    }

    patients := []*PatientEntity{}  
    q := datastore.NewQuery(KINDPATIENT).Filter("FirstName =",patient.FirstName) 

    keys, err := q.GetAll(ctx, &patients)

    if err != nil {
        // Handle error
        return
    }

    json.NewEncoder(res).Encode(patients)
}

我需要搜索结构的所有值。我该如何解决。

【问题讨论】:

  • 这篇文章包含了完成这个任务所需的一切,并附有示例代码:Index Selection and Advanced Search
  • 请在NewQuery之前显示patient的值,在GetAll之后显示patientsKINDPATIENT的值。您可能还想查询数据存储以确保您的数据符合预期。
  • 我想使用 PHONE 或 FIRSTNAME 或 LASTNAME 过滤值。是否可以使用 FILTER 使用 DATASTORE。

标签: google-app-engine go datastore


【解决方案1】:

如果我理解正确,您正在尝试将过滤器与OR 结合使用。根据the docs,这是不可能的:

Cloud Datastore 目前仅原生支持组合过滤器 使用 AND 运算符。

对此有一个 tracking issue,但它已经存在了很长时间没有采取任何行动。

您可以改为为每个过滤器发出单独的查询,然后合并结果(查询名字,然后查询姓氏,然后查询电话。最后:合并所有返回结果,同时删除重复项)。

类似于(伪代码,但这是 OR 搜索的逻辑):

var results []Patients
if firstname != "" {
  results = append(results, query("firstname = ", firstname)
}
if lastname != "" {
  results = append(results, query("lastname = ", lastname)
}
etc...
removeDuplicates(results)

【讨论】:

  • if (patient.FirstName != "" ){ q = datastore.NewQuery(KINDPATIENT).Filter("FirstName=",patient.FirstName) }else if(patient.LastName != ""){ q = datastore.NewQuery(KINDPATIENT).Filter("LastName =", patient.LastName) }else if(patient.Phone != ""){ q = datastore.NewQuery(KINDPATIENT).Filter("Phone =", patient.Phone) } 这样我做的. 是否有意义
  • 您没有进行 OR 搜索。如果我同时指定firstnamelastname,您将根本不会搜索lastname。我已经用你想要做的伪代码更新了我的答案。
  • 上面的代码对我不起作用我收到一个错误,显示不能使用查询,removeDuplicates(undefined) 我正在使用 datastore.NewQuery
  • 我确实说过这是伪代码,而不是实际代码。您必须自己编写removeDuplicatesquery(...) 代表构建/发送查询并解析结果。
  • 我坚持这个。你能帮帮我吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-31
  • 2017-05-25
  • 2018-06-01
相关资源
最近更新 更多