Gorm 非常慢

Gorm extremely slow

Gorm 似乎非常慢。

type Ad struct {
    AdId        string `json:"adId" gorm:"column:adId"`
    Attributes  string `json:"attributes" gorm:"column:attributes"`
    Title       string `json:"title" gorm:"column:title"`
    Description string `json:"description" gorm:"column:description"`
    Image       string `json:"image" gorm:"column:image"`
    Url         string `json:"url" gorm:"column:url"`
    Price       int    `json:"price" gorm:"column:price"`
    Address    string    `json:"address" gorm:"column:address"`
    Latitude   float64   `json:"latitude" gorm:"column:latitude"`
    Longitude  float64   `json:"longitude" gorm:"column:longitude"`
    PostedDate time.Time `json:"postedDate" gorm:"column:postedDate"`
}

db.Table("Kijiji").Find(&listing).Where("adId = ?", m["id"][0])

上次查询差不多用了60s。而如果我使用 "database/sql" mysql.QueryRow() 它不到 500 毫秒。

知道为什么吗?

更新:

变慢发生在这个 callback_query.go 看来这个函数正在遍历整个 table 的 20k 记录。

func queryCallback(scope *Scope) {
    ..........
        if rows, err := scope.SQLDB().Query(scope.SQL, scope.SQLVars...); scope.Err(err) == nil {
            defer rows.Close()
            columns, _ := rows.Columns()
            for rows.Next() {
                scope.db.RowsAffected++

                elem := results
                if isSlice {
                    elem = reflect.New(resultType).Elem()
                }
                scope.scan(rows, columns, scope.New(elem.Addr().Interface()).Fields())
            ..................
        }
    }
}

我该如何解决这个问题?

你做反了。 Find 执行查询并获取行。您希望 db.Table("Kijiji").Where("adId = ?", m["id"][0]).Find(&listing) 在 获取所有内容之前应用 where 条件