예제 #1
0
    def analytics_query(
            self,  # type: Cluster
            statement,  # type: str,
            *options,  # type: AnalyticsOptions
            **kwargs):
        # type: (...) -> AnalyticsResult
        """
        Executes an Analytics query against the remote cluster and returns a AnalyticsResult with the results
        of the query.

        :param statement: the analytics statement to execute
        :param options: the optional parameters that the Analytics service takes based on the Analytics RFC.
        :return: An AnalyticsResult object with the results of the query or error message if the query failed on the server.
        :raise: :exc:`~.exceptions.AnalyticsException` errors associated with the analytics query itself.
            Also, any exceptions raised by the underlying platform - :class:`~.exceptions.TimeoutException`
            for example.
        """
        # following the query implementation, but this seems worth revisiting soon
        self._check_for_shutdown()
        itercls = kwargs.pop('itercls', AnalyticsResult)
        opt = AnalyticsOptions()
        opts = list(options)
        for o in opts:
            if isinstance(o, AnalyticsOptions):
                opt = o
                opts.remove(o)

        return self._maybe_operate_on_an_open_bucket(
            CoreClient.analytics_query,
            AnalyticsException,
            opt.to_analytics_query(statement, *opts, **kwargs),
            itercls=itercls,
            err_msg='Analytics queries require an open bucket')
예제 #2
0
 def test_query_positional_params(self):
     rows_attempt = self.try_n_times(10, 3, self.assertQueryReturnsRows,
                                     'SELECT * FROM `{}` WHERE `type` = $1 LIMIT 1'.format(
                                         self.dataset_name),
                                     AnalyticsOptions(positional_parameters=["brewery"]))
     print(rows_attempt)
     return self.checkResult(rows_attempt, lambda result:  self.assertEqual("brewery", result[0][self.dataset_name]['type']))
예제 #3
0
 def test_query_named_parameters_override(self):
     rows_attempt = self.try_n_times(10, 3, self.assertQueryReturnsRows,
                                     "SELECT * FROM `{}` WHERE `type` = $btype LIMIT 1".format(
                                         self.dataset_name),
                                     AnalyticsOptions(named_parameters={
                                                      "btype": "jfjfjfjf"}),
                                     btype="brewery")
     return self.checkResult(rows_attempt, lambda result: self.assertEqual("brewery", result[0][self.dataset_name]['type']))
예제 #4
0
async def analytics_query(cluster):
    try:
        result = cluster.analytics_query(
            "SELECT a.* FROM `travel-sample`.inventory.airports a WHERE a.country = $country LIMIT 10",
            AnalyticsOptions(named_parameters={"country": "France"}))
        async for row in result:
            print("Found row: {}".format(row))
    except CouchbaseException as ex:
        print(ex)
예제 #5
0
async def simple_query(cluster):
    try:
        result = cluster.analytics_query(
            "SELECT id, country FROM airports a WHERE a.country = $country LIMIT 10",
            AnalyticsOptions(named_parameters={"country": "France"}))
        async for row in result:
            print("Found row: {}".format(row))
    except CompilationFailedException as ex:
        print(ex)
예제 #6
0
    def test_bad_query_context(self):
        # test w/ no context
        result = self.cluster.analytics_query("SELECT * FROM beers LIMIT 2")
        with self.assertRaises(DatasetNotFoundException):
            result.rows()

        # test w/ bad scope
        q_context = 'default:`{}`.`{}`'.format(self.bucket_name, 'fake-scope')
        result = self.cluster.analytics_query(
            "SELECT * FROM beers LIMIT 2", AnalyticsOptions(query_context=q_context))
        with self.assertRaises(DataverseNotFoundException):
            result.rows()
예제 #7
0
    def test_cluster_query_context(self):
        q_context = 'default:{}'.format(self.dataverse_fqdn)
        # test with QueryOptions
        a_opts = AnalyticsOptions(query_context=q_context)
        result = self.cluster.analytics_query(
            "SELECT * FROM beers LIMIT 2", a_opts)
        self.assertRows(result, 2)

        # test with kwargs
        result = self.cluster.analytics_query(
            "SELECT * FROM beers LIMIT 2", query_context=q_context)
        self.assertRows(result, 2)
예제 #8
0
    def test_bad_scope_query(self):
        scope = self.bucket.scope(self.beer_sample_collections.scope)
        q_context = 'default:`{}`.`{}`'.format(self.bucket_name, 'fake-scope')
        result = scope.analytics_query("SELECT * FROM beers LIMIT 2",
                                       AnalyticsOptions(query_context=q_context))
        with self.assertRaises(DataverseNotFoundException):
            result.rows()

        q_context = 'default:`{}`.`{}`'.format(
            'fake-bucket', self.beer_sample_collections.scope)
        result = scope.analytics_query("SELECT * FROM beers LIMIT 2",
                                       query_context=q_context)
        with self.assertRaises(DataverseNotFoundException):
            result.rows()
예제 #9
0
 def test_scope_query_with_named_params_in_options(self):
     scope = self.bucket.scope(self.beer_sample_collections.scope)
     result = scope.analytics_query("SELECT * FROM beers WHERE META().id LIKE $brewery LIMIT 1",
                                    AnalyticsOptions(named_parameters={'brewery': '21st_amendment%'}))
     self.assertRows(result, 1)
예제 #10
0
 def to_analytics_options(self, **kwargs):
     final_opts = {**self, **kwargs}
     return AnalyticsOptions(
         **{k: v
            for k, v in final_opts.items() if k in self.OPTION_KEYS})
예제 #11
0
 def _to_analytics_options(option  # type: BaseAnalyticsIndexManagerOptions
                           ):
     return option.to_analytics_options() if option else AnalyticsOptions()
from twisted.internet import reactor

from txcouchbase.cluster import TxCluster
from couchbase.cluster import ClusterOptions
from couchbase.auth import PasswordAuthenticator
from couchbase.analytics import AnalyticsOptions


def handle_query_results(result):
    for r in result.rows():
        print("query row: {}".format(r))
    reactor.stop()


cluster = TxCluster(
    "couchbase://localhost",
    ClusterOptions(PasswordAuthenticator("Administrator", "password")))

# create a bucket object
bucket = cluster.bucket("travel-sample")
# create a collection object
cb = bucket.default_collection()

d = cluster.analytics_query(
    "SELECT id, country FROM airports a WHERE a.country = $country LIMIT 10",
    AnalyticsOptions(named_parameters={"country": "France"}))
d.addCallback(handle_query_results)

reactor.run()
# end::simple_query[]