Tusshu
Tusshu

Reputation: 1734

ArangoDB function db.Query(ctx, query, bindVars) returns no data

Code below the comment 'Querying documents with bind variables' does not product the expected record count of 1.

import (
  "fmt"
  driver "github.com/arangodb/go-driver"
  "github.com/arangodb/go-driver/http"
  "context"
)
type Book struct {
    Title   string `json:"title"`
    NoPages int    `json:"no_pages"`
}
func main() {
    conn, err := http.NewConnection(http.ConnectionConfig {
    Endpoints: []string{"http://root@localhost:8529"},
    })
    if err != nil { panic(err) }

    c, err := driver.NewClient(driver.ClientConfig{
       Connection: conn,
    })

    // Open "examples_books" database
    db, err := c.Database(nil, "examples_books")
    if err != nil { panic(err) }

    // Open "books" collection
    col, err := db.Collection(nil, "books")
    if err != nil { panic(err) }

    // Create document
    book := Book{
        Title:   "ArangoDB Cookbook",
        NoPages: 257,
    }
    meta, err := col.CreateDocument(nil, book)
    if err != nil { panic(err) }
    fmt.Printf("Created document in collection '%s' in database 
    '%s'\n", col.Name(), db.Name())

    // Read the document back
    var result Book
    if _, err := col.ReadDocument(nil, meta.Key, &result); err != nil 
     { panic(err)}
    fmt.Printf("Read book '%+v'\n", result)

    //Querying documents with bind variables
    ctx := context.Background()
    query := "FOR d IN books FILTER d.NoPages == @noPages RETURN d"
    bindVars := map[string]interface{}{
      "noPages": 257,
    }
    cursor, err := db.Query(ctx, query, bindVars)
    if err != nil {
       panic(err)
    }
    defer cursor.Close()
    resultCount := cursor.Count()
    fmt.Printf("Number of records = %+v\n", resultCount)
}

Go version 1.13.7; ArangoDB 3.6.1, MacOS Catalina 10.15.3

Upvotes: 0

Views: 355

Answers (2)

user22229308
user22229308

Reputation: 1

the context specified while running db.Query() must have been generated with the WithQueryCount(nil, true) function from the driver (documentation here: https://pkg.go.dev/github.com/arangodb/go-driver#WithQueryCount)

i.e. adding a ctx := driver.WithQueryCount(context.Background(), true) and using ctx in your db.Query() call should work

Upvotes: 0

Adam Janikowski
Adam Janikowski

Reputation: 26

I can see you have field NoPages of struct Book exposed as no_pages in json definition. Can you try to change query to:

query := "FOR d IN books FILTER d.no_pages == @noPages RETURN d"

Upvotes: 1

Related Questions