无法在Golang中对数据存储类型的实体进行排序

In my application, I use go 1.11 as backend. It performs CRUD operations in google datastore. I can retrieve entities from a particular kind but in an unpredictable order. I am using below datastore module:

"cloud.google.com/go/datastore"

My struct for this is:

type RuleDS struct {
    Id              string          `json:"id" datastore:"id"`
    Name            string          `json:"name" datastore:"name"`
    Salience        int             `json:"salience" datastore:"salience"`
    CreatedAt       time.Time       `json:"createdAt" datastore:"createdAt"`
}

My code to sort entities in order is as below:

    var rulesDSArr  []RuleDS
    query := datastore.NewQuery("Rule").Order("-Salience")
    _, errDS := s.DataLayer.GetAll(ctx, query, &rulesDSArr)
    if errDS!= nil{
      log.Errorf(ctx,"Error while getting rules : %v",errDS)
    }

I also checked logs where query formed is:

&{kind:Rule ancestor:<nil> filter:[] order:[{FieldName:Salience Direction:true}] projection:[] distinct:false distinctOn:[] keysOnly:false eventual:false limit:-1 offset:0 start:[] end:[] namespace: trans:<nil> err:<nil>}

In google datastore, I have tried by making Salience property indexed as well as nonindexed but nothing worked for me. I don't know what I am doing wrong here due to which I get null as a result. If I remove .Order("-Salience") from query statement, I get all rules again.

It sounds like you don't have any values of Salience indexed. The .Order("-Salience") uses an index on the Salience value, so any entities that don't have a value for Salience indexed will not show up in the results. That said, the value in Cloud Datastore seems to be salience, so you should try .Order("-salience").

Things you can try in the cloud console:

  • select * from Rule order by salience desc
  • select * from Rule order by Salience desc

If neither give results then you don't have any values of Salience indexed and you'll have to rewrite your entities.