Как запросить Couchbase с помощью Java API - PullRequest
0 голосов
/ 15 октября 2018

Я пытаюсь сделать запрос из примера пива Couchbase.

Этот запрос прекрасно работает в пользовательском интерфейсе браузера Couchbase:

select category, style from `beer-sample` where style like 'Imperial%'

Результаты:

[
  {
    "category": "North American Ale",
    "style": "Imperial or Double India Pale Ale"
  },
...
]

Но когда я перевожу запрос в Java, я получаю очень странные результаты.(Да, я знаю, что открываю / закрываю соединение не в том месте, просто делаю это для быстрого изучения синтаксиса / возможностей Couchbase).

Java-код:

@RequestMapping("/hellocouchbase")
public ResponseEntity<List<JsonObject>> metrics() {

    Cluster cluster = CouchbaseCluster.create();
    cluster.authenticate(username, passwd);

    Bucket bucket = cluster.openBucket("beer-sample");

    N1qlQueryResult result = bucket.query(N1qlQuery.simple("select category, style from `beer-sample` where style like 'Imperial%'"));

    List<N1qlQueryRow> results = result.allRows();      
    List<JsonObject> answer = new ArrayList<>(results.size());

    for(N1qlQueryRow row:results) {
        answer.add(row.value());
    }

    cluster.disconnect();       
    return ResponseEntity.status(200).body(answer);
}

Результаты:

[
{"cryptoManager":null,"empty":false,"names":["style","category"]},{"cryptoManager":null,"empty":false,"names":["style","category"]},
...
]

Может кто-нибудь объяснить, как заставить Java-запрос давать те же результаты, что и прямой запрос?

Ответы [ 2 ]

0 голосов
/ 17 октября 2018

По какой-то причине изменение этого

answer.add(row.value());

на это

answer.add(row.value().toMap());

исправило это для меня.Не знаю почему, учитывая, что оригинальная версия, по-видимому, отлично работает для других людей здесь.

Полное решение для справки:

@RequestMapping("/hellocouchbase")
public ResponseEntity<List<Map<String,Object>>> metrics() {

    Cluster cluster = CouchbaseCluster.create();
    cluster.authenticate(username, passwd);

    Bucket bucket = cluster.openBucket("beer-sample");

    N1qlQueryResult result = bucket.query(N1qlQuery.simple("select category, style from `beer-sample` where style like 'Imperial%'"));

    List<N1qlQueryRow> results = result.allRows();      
    List<Map<String,Object>> answer = new ArrayList<>(results.size());

    for(N1qlQueryRow row:results) {
        answer.add(row.value().toMap());
    }

    cluster.disconnect();       
    return ResponseEntity.status(200).body(answer);
}
0 голосов
/ 16 октября 2018

Попробуйте создать нового пользователя и добавить к нему все привилегии (просто чтобы быть уверенным, что вы не нарушаете никаких ограничений безопасности).

Ваш код работает для меня:

    Cluster cluster = CouchbaseCluster.create();
    cluster.authenticate("test", "couchbase"); //user and password that I created

    Bucket bucket = cluster.openBucket("beer-sample");

    N1qlQueryResult result = bucket.query(N1qlQuery.simple("select category, style from `beer-sample` where style like 'Imperial%'"));

    List<N1qlQueryRow> results = result.allRows();
    List<JsonObject> answer = new ArrayList<>(results.size());

    for(N1qlQueryRow row:results) {
        answer.add(row.value());
        System.out.println(row);
    }

    cluster.disconnect();

Выход:

{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
...
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
{"category":"North American Ale","style":"Imperial or Double Red Ale"}
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
{"category":"North American Ale","style":"Imperial or Double India Pale Ale"}
...