i need to save some data where it consist of a fields called ID which is an uuid im using golang and olivere elastic search package here is my code
type Space struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
}
After doing some conversions
js := string(data)
// upto this place there is no error or warnings
ind, err := esclient.Index().
Index(Type).
BodyJson(js).
Do(ctx)
Here is the error it throws
failed to parse field [id] of type [long] in document with id
'gPmI8HIBCIO6Ejb-Y51D'. Preview of field's value:
'a5c723c5-1f6e-457f-9556-47b7ebcfd183'
The Error message is very clear that you are trying to store a5c723c5-1f6e-457f-9556-47b7ebcfd183 which is a string and not long as id field is mapped as long in your elasticsearch mapping.
It's even also telling that you got an error for document with _id having gPmI8HIBCIO6Ejb-Y51D as value, so you can find this document and correct it.
Please send the proper value of the below field, valid long in your case in order to solve the issue.
ID string `json:"id"`
Refer this code from Elasticsearch which parse the values and throws the exception, if you want to get more code level details.
Related
I'm new to Golang and I need to know how to access the value from a struct of the format:
type CurrentSkuList struct {
SubscriptionNumber string `json:"subscriptionNumber`
Quantity int `json:"quantity"`
SubscriptionProducts []struct {
ID int `json:"id"`
ActiveStartDate int `json:"activeStartDate"`
ActiveEndDate int `json:"activeEndDate"`
Status string `json:"status"`
Sku string `json:"sku"`
ChildIDs []int `json:"childrenIds"`
} `json:"subscriptionProducts"`
}
For example, if I have a variable currentSkus of type CurrentSkuList and I need to access only Sku and Status values, is there a way to do something like:
currentSkus.SubscriptionProducts.Sku?
EDIT! When I try to access currentSkus.Quantity I get a compiler error undefined (type []util.CurrentSkuList has no field or method Quantity).
Yeah, there is a way. You can access by the . syntax you proposed. In this case, CurrentSkuList is returning an slice of SubscriptionProduct, you know that because of the [] struct part. Then you would have to access to the data this way:
currentSkus.SubscriptionProducts[index].Sku
Let's say I have the following types.
type Contract struct {
Id string `json:"id" gorm:"column:uuid"`
Name string `json:"name" gorm:"column:name"`
Description string `json:"descr" gorm:"column:descr"`
ContractTypeId int `json:"contract_type_id" gorm:"column:contract_type_id"`
}
type ContractModel struct {
Id string `json:"id" gorm:"column:uuid"`
Name string `json:"name" gorm:"column:name"`
Description string `json:"descr" gorm:"column:descr"`
}
I have a SQL query using gorm to scan results into a contract object.
How can I map the values from the contract object into contractModel object?
I tried using the package go-automapper as such:
automapper.Map(contract, ContractModel{})
I want to drop the ContractTypeId.
Can I do this for multiple types in a list?
var contractModels []ContractModel
automapper.Map(contracts, &contractModels)
You can do either:
models := []ContractModel{}
automapper.Map(contracts, &models)
Or call automapper.Map in a loop:
models := make([]ContractModel, len(contracts))
for i := range contracts {
automapper.Map(contracts[i], &models[i])
}
You should be aware that automapper uses reflection behind the scenes and thus is much slower than straight forward non-polymorphic copying like #ThinkGoodly suggests. It's a totally fine solution if performance isn't top priority though.
I have two structures.
EventForm is the structure that is used to parse the POST body of a request.
EventTable is used for creating the MYSQL table structure and finding/creating rows.
I want to merge EventForm with EventTable so that fields like ID cannot be overridden via the POST body. I am not able to convert the type of EventForm to EventTable since you cannot convert a struct to a different type if the fields do not 100% match. So my question is what is the best way to merge these two structs? If it is not plausible to merge these two structs how could I best solve this problem?
package models
import "time"
// EventTable table structure of "events"
type EventTable struct {
EventForm `xorm:"extends"`
ID int `xorm:"autoincr pk 'id'" json:"id"`
Created time.Time `xorm:"not null created" json:"created"`
Updated time.Time `xorm:"not null updated" json:"updated"`
}
// TableName table name of EventTable
func (u *EventTable) TableName() string {
return "events"
}
// EventForm the structure that is received via an API call
type EventForm struct {
Title string `xorm:"not null" json:"title" required:"true"`
Description string `xorm:"not null" json:"description" required:"true"`
Owner string `xorm:"not null" json:"owner" required:"true"`
Lat string `xorm:"not null" json:"lat" required:"true"`
Lng string `xorm:"not null" json:"lng" required:"true"`
}
I am with #mkopriva and don't fully understand what the problem is. Assuming you are receiving EventForm from some API call
evtForm := GetSomeEventForm()
evtTable := &models.EventTable{ EventForm: evtForm, Created: time.Now() }
someORMProbably.Insert(evtTable)
I have a Golang struct called Person where all the properties have to be exported:
type Person struct {
Id string
Name string
}
Now I need to encode my MongoDB BSON response to this Person struct. The BSON looks like:
{
"_id": "ajshJSH78N",
"Name": "Athavan Kanapuli"
}
The Golang code to encode the BSON is:
mongoRecord := Person{}
c := response.session.DB("mydb").C("users")
err := c.Find(bson.M{"username": Credentials.Username, "password": Credentials.Password}).One(&mongoRecord)
The Problem:
_id is not getting encoded into Id
If I change the Person property into _Id, then it won't be exported.
How can I solve this problem?
Define your struct with json tag-
type Person struct {
Id string `json:"_id"`
Name string // this field match with json, so mapping not need
}
I tried to put a json tag like ,
type Person struct {
Id string `json:"_id"`
Name string // this field match with json, so mapping not need
}
But still it didn't work. Because the Mongodb returns '_id' which is of type bson.ObjectId . Hence changing the Struct tag to bson:"_id" and the type of the Person struct has been changed from string to bson.ObjectId. The changes done are as follows ,
type Person struct {
Id bson.ObjectId `bson:"_id"`
Name string
UserName string
IsAdmin bool
IsApprover bool
}
And It works!
I don't understand the significance of struct tags. I have been looking them, and noticed that they can be used with reflect package. But I don't know any practical uses of them.
type TagType struct { // tags
field1 bool “An important answer”
field2 string “The name of the thing”
field3 int “How much there are”
}
The use of tags strongly depends on how your struct is used.
A typical use is to add specifications or constraints for persistence or serialisation.
For example, when using the JSON parser/encoder, tags are used to specify how the struct will be read from JSON or written in JSON, when the default encoding scheme (i.e. the name of the field) isn't to be used.
Here are a few examples from the json package documentation :
// Field is ignored by this package.
Field int `json:"-"`
// Field appears in JSON as key "myName".
Field int `json:"myName"`
// Field appears in JSON as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
Field int `json:"myName,omitempty"`
// Field appears in JSON as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `json:",omitempty"`
Example of use is json encoding/decoding in encoding/json:
type TagType struct {
field1 bool `json:"fieldName"`
field2 string `json:",omitempty"`
}
More details in documentation: encoding/json
You can also use XML struct tags as shown below
type SearchResult struct {
Title string `xml:"title,attr"`
Author string `xml:"author,attr"`
Year string `xml:"hyr,attr"`
ID string `xml:"owi,attr"`
}