有什么方法可以在 Golang 中处理 Google Datastore Kind 属性 带空格的名称吗?

Is there any way to handle Google Datastore Kind Property names with spaces in Golang?

我 运行 遇到了 Datastore 的严重问题,似乎没有任何解决方法。

我正在使用 Google Appengine 数据存储包将投影查询结果拉回到 Appengine 内存中进行操作,这是通过将每个实体表示为一个 Struct 来实现的,每个 Struct 字段对应一个属性 名字,像这样:

type Row struct {
Prop1    string
Prop2    int
}

这很好用,但我已将查询扩展到读取其他 属性 有空格的名称。虽然查询运行良好,但它无法将数据拉回到结构中,因为它希望将给定值放入具有相同命名约定的结构中,我遇到了这种错误:

datastore: cannot load field "Viewed Registration Page" into a "main.Row": no such struct field

显然 Golang 不能像这样表示结构字段。有一个相关类型的字段,但没有明显的方法告诉查询将它放在那里。

最好的解决方案是什么?

干杯

我所知道的所有编程语言都将 space 视为 variable/constant 名称的结尾。显而易见的解决方案是避免在 属性 名称中使用 space。

我还要指出,属性 名称成为每个实体和每个索引条目的一部分。我不知道 Google 是否以某种方式压缩了它们,但无论如何我都倾向于使用简短的 属性 名称。

您可以使用注释重命名属性。

来自docs

// A and B are renamed to a and b.
// A, C and J are not indexed.
// D's tag is equivalent to having no tag at all (E).
// I is ignored entirely by the datastore.
// J has tag information for both the datastore and json packages.
type TaggedStruct struct {
    A int `datastore:"a,noindex"`
    B int `datastore:"b"`
    C int `datastore:",noindex"`
    D int `datastore:""`
    E int
    I int `datastore:"-"`
    J int `datastore:",noindex" json:"j"`
}

实际上 Go 支持使用标签将实体 属性 名称映射到不同的结构字段名称(有关详细信息,请参阅此答案:What are the use(s) for tags in Go?)。

例如:

type Row struct {
    Prop1    string `datastore:"Prop1InDs"`
    Prop2    int    `datastore:"p2"`
}

但是如果您尝试使用包含 space.

的 属性 名称,datastore 包的 Go 实现会出现混乱

总结一下:你不能将具有 space 的 属性 名称映射到 Go 中的结构字段(这是一个实现限制将来可能会改变)。

但好消息是您仍然可以加载这些实体,只是不加载到结构值中。

您可以将它们加载到 datastore.PropertyList 类型的变量中。 datastore.PropertyList 基本上是 datastore.Property 的一部分,其中 Property 是一个结构,其中包含 属性 的名称、它的值和其他信息。

这是可以做到的:

k := datastore.NewKey(ctx, "YourEntityName", "", 1, nil) // Create the key
e := datastore.PropertyList{}

if err := datastore.Get(ctx, k, &e); err != nil {
    panic(err) // Handle error
}

// Now e holds your entity, let's list all its properties.
// PropertyList is a slice, so we can simply "range" over it:
for _, p := range e {
    ctx.Infof("Property %q = %q", p.Name, p.Value)
}

如果您的实体有 属性 "Have space" 且值为 "the_value",您将看到例如:

2016-05-05 18:33:47,372 INFO: Property "Have space" = "the_value"

请注意,您可以在结构上实现 datastore.PropertyLoadSaver 类型并在后台处理它,因此基本上您仍然可以将此类实体加载到结构值中,但您必须自己实现。

但是争取实体名称和 属性 名称没有 space。如果你允许这些,你会让你的生活更加艰难和悲惨。