如何在golang中使用沙发数据库查询限制

时间:2017-10-12 17:13:59

标签: go couchdb

我在golang上使用couchdb,我需要选择限制为1的记录,我尝试使用下面的芒果查询。

{"selector": {"$and": [{"memid": {"$gt": "null"}}, {"custid": {"$gt": "null"}}]},"limit" : 1}

以上查询在浏览器上的fauxton上工作得很好,但是在golang中也不行,所有结果都没有应用限制。

golang查询:

queryString := fmt.Sprintf("{\"selector\": {\"$and\": [{\"memid\": {\"$gt\": \"%s\"}}, {\"custid\": {\"$gt\": \"%s\"}}]},\"limit\" : \"%d\"}", "null", "null",1)
queryResults, err := getQueryResultForQueryString(stub, queryString)

getQueryResultForQueryString的函数定义:

func getQueryResultForQueryString(stub shim.ChaincodeStubInterface, queryString string) ([]byte, error) {

    fmt.Printf("- getQueryResultForQueryString queryString:\n%s\n", queryString)

    resultsIterator, err := stub.GetQueryResult(queryString)
    if err != nil {
        return nil, err
    }
    defer resultsIterator.Close()

    // buffer is a JSON array containing QueryRecords
    var buffer bytes.Buffer
    buffer.WriteString("[")

    bArrayMemberAlreadyWritten := false

    for resultsIterator.HasNext() {
        queryResponse, err := resultsIterator.Next()
        if err != nil {
            return nil, err
        }
        // Add a comma before array members, suppress it for the first array member
        if bArrayMemberAlreadyWritten == true {
            buffer.WriteString(",")
        }
        buffer.WriteString("{\"Key\":")
        buffer.WriteString("\"")
        buffer.WriteString(queryResponse.Key)
        buffer.WriteString("\"")

        buffer.WriteString(", \"Record\":")
        // Record is a JSON object, so we write as-is
        buffer.WriteString(string(queryResponse.Value))
        buffer.WriteString("}")
        bArrayMemberAlreadyWritten = true
    }
    buffer.WriteString("]")

    fmt.Printf("- getQueryResultForQueryString queryResult:\n%s\n", buffer.String())

    return buffer.Bytes(), nil
}

1 个答案:

答案 0 :(得分:0)

请查看github.com/leesper/couchdb-golang

func (d *Database) Query(fields []string, selector string, sorts []string, limit, skip, index interface{}) ([]map[string]interface{}, error)