id stringlengths 14 15 | text stringlengths 56 2.52k | source stringlengths 30 97 |
|---|---|---|
2c1eba00554c-0 | The Hyper-Fast Database that Truly Scales
Simply get the best out of the SQL and NoSQL worlds. Whatever the complexity, volume and velocity of data, CrateDB allows you to perform complex queries in milliseconds, where other database technologies simply can’t.
Get started for free
Talk to an expert
Talk to our engin... | https://cratedb.com/index.html |
2c1eba00554c-1 | IoT & Sensor Data
Geospatial Tracking
Log Analysis
/* Based on device data, this query returns the average
* of the battery level for every hour for each device_id
*/
WITH avg_metrics AS (
SELECT device_id,
DATE_BIN('1 hour'::INTERVAL, time, 0) AS period,
AVG(battery_level) AS avg_... | https://cratedb.com/index.html |
2c1eba00554c-2 | | 1480802400000 | demo000016 | iobeam | 36.06060606060606 |
| 1480806000000 | demo000016 | iobeam | 35.45 |
| 1480802400000 | demo000025 | iobeam | 12 |
| 1480806000000 | demo000025 | iobeam | 16.475 |
+---------------+------------+--------------+-----------... | https://cratedb.com/index.html |
2c1eba00554c-3 | +------------+--------------------------+
Statement
Result
/* Based on the location of the International Space Station,
* this query returns the 10 closest capital cities from
* the last known position
*/
SELECT city as "City Name",
country as "Country",
DISTANCE(... | https://cratedb.com/index.html |
2c1eba00554c-4 | Statement
Result
/*
* Based on system event logs, this query calculates:
* - a filter for specific messages using a full-text index
* - the number of entries per minute
* - the average scoring ratio for each matched row
*/
SELECT DATE_TRUNC('minute', receivedat) AS event_time,
COUNT(*) AS ... | https://cratedb.com/index.html |
2c1eba00554c-5 | | 1620219720000 | 13 | 1.5637413492569556 |
+---------------+---------+--------------------+
Statement
Result
Upcoming Events
October 10, 2023 - October 11, 2023
14:00 - 16:00 CET
Webinar
CrateDB Workshop 2nd edition
CrateDB Workshop is a hands-on learning experience for novel and ex... | https://cratedb.com/index.html |
6fd5a62e0b2e-0 | Feedback
Suggest improvement
Edit page
View page source
latest
CrateDB Python Client¶
Table of contents
Introduction
Documentation
Project information
Introduction¶
The Python client library for CrateDB implements the Python Database API
Specification v2.0 (PEP 24... | https://cratedb.com/docs/python/index.html |
6fd5a62e0b2e-1 | cursor.close()
Connect to CrateDB Cloud.
# Connect using DB API.
from crate import client
connection = client.connect(
servers="https://example.aks1.westeurope.azure.cratedb.net:4200",
username="admin",
password="<PASSWORD>")
SQLAlchemy¶
The CrateDB dialect for SQLAlchemy offers convenient ORM access and su... | https://cratedb.com/docs/python/index.html |
6fd5a62e0b2e-2 | engine = sa.create_engine(dburi, echo=True)
with engine.connect() as connection:
df = pd.read_sql(sql=sa.text(query), con=connection)
df.info()
print(df)
Data types¶
The DB API driver and the SQLAlchemy dialect support CrateDB’s data types to different degrees. For more information,
please consult the Data ... | https://cratedb.com/docs/python/index.html |
6fd5a62e0b2e-3 | License¶
The project is licensed under the terms of the Apache 2.0 license, like
CrateDB itself, see LICENSE. | https://cratedb.com/docs/python/index.html |
7e326c7c9930-0 | Feedback
Suggest improvement
Edit page
View page source
latest
Other connectivity options for Python¶
Introduction¶
Using the PostgreSQL wire protocol interface of CrateDB,
there are a few other connectivity options for Python. This section enumerates
the verified... | https://cratedb.com/docs/python/en/latest/other-options.html |
3ac90d84908a-0 | Feedback
Suggest improvement
Edit page
View page source
latest
CrateDB Python Client¶
Table of contents
Introduction
Documentation
Project information
Introduction¶
The Python client library for CrateDB implements the Python Database API
Specification v2.0 (PEP 24... | https://cratedb.com/docs/python/en/latest/index.html |
3ac90d84908a-1 | cursor.close()
Connect to CrateDB Cloud.
# Connect using DB API.
from crate import client
connection = client.connect(
servers="https://example.aks1.westeurope.azure.cratedb.net:4200",
username="admin",
password="<PASSWORD>")
SQLAlchemy¶
The CrateDB dialect for SQLAlchemy offers convenient ORM access and su... | https://cratedb.com/docs/python/en/latest/index.html |
3ac90d84908a-2 | engine = sa.create_engine(dburi, echo=True)
with engine.connect() as connection:
df = pd.read_sql(sql=sa.text(query), con=connection)
df.info()
print(df)
Data types¶
The DB API driver and the SQLAlchemy dialect support CrateDB’s data types to different degrees. For more information,
please consult the Data ... | https://cratedb.com/docs/python/en/latest/index.html |
3ac90d84908a-3 | License¶
The project is licensed under the terms of the Apache 2.0 license, like
CrateDB itself, see LICENSE. | https://cratedb.com/docs/python/en/latest/index.html |
b372db211a3d-0 | Feedback
Suggest improvement
Edit page
View page source
latest
CrateDB Python Client – all pages¶
Table of contents
Getting started
Install
Interactive use
Set up as a dependency
Next steps
Connect to CrateDB
Connect to a single node
Connect to multiple nodes
Conn... | https://cratedb.com/docs/python/en/latest/index-all.html |
5a248a93d3ad-0 | Feedback
Suggest improvement
Edit page
View page source
latest
SQLAlchemy support¶
Table of contents
Introduction
Connecting
Database URLs
Getting a connection
Tables
Table definition
Extension types
Querying
Aggregate functions
Fulltext search
Introduction¶
SQLAl... | https://cratedb.com/docs/python/en/latest/sqlalchemy.html |
5a248a93d3ad-1 | can add the query parameter ?ssl=true to the database URI.
Example database URIs:
crate://localhost:4200
crate://crate-1.vm.example.com:4200
crate://username:password@crate-2.vm.example.com:4200/?ssl=true
crate://198.51.100.1:4200
Tip
If <HOST> is blank (i.e. the database URI is just crate://), then
localhost:4200 will... | https://cratedb.com/docs/python/en/latest/sqlalchemy.html |
5a248a93d3ad-2 | >>> engine = sa.create_engine(
... 'crate://',
... connect_args={
... 'servers': ['198.51.100.1:4200', '198.51.100.2:4200'],
... 'ca_cert': '<PATH_TO_CA_CERT>',
... }
... )
In order to disable SSL verification, use verify_ssl_cert = False, like:
>>> engine = sa.create_engine(
... 'crate:... | https://cratedb.com/docs/python/en/latest/sqlalchemy.html |
5a248a93d3ad-3 | >>> class Character(Base):
...
... __tablename__ = 'characters'
... __table_args__ = {
... 'crate_number_of_shards': 3
... }
...
... id = sa.Column(sa.String, primary_key=True, default=gen_key)
... name = sa.Column(sa.String, crate_index=False)
... name_normalized = sa.Column(sa.String, ... | https://cratedb.com/docs/python/en/latest/sqlalchemy.html |
5a248a93d3ad-4 | the mapping (so SQLAlchemy doesn’t try to update them as if they were columns)
Disable the columnstore of the even_more_details column using crate_columnstore=False
Add a created_at column whose default value is set by CrateDB’s now() function.
Tip
This example table is used throughout the rest of this document.
See al... | https://cratedb.com/docs/python/en/latest/sqlalchemy.html |
5a248a93d3ad-5 | ... ts = sa.Column(sa.DateTime, server_default=sa.func.current_timestamp())
... level = sa.Column(sa.String)
... message = sa.Column(sa.String)
>>> log = Log(level="info", message="Hello World")
>>> session.add(log)
>>> session.commit()
>>> log.id
...
Auto-generated primary key¶
CrateDB 4.5.0 added the gen_... | https://cratedb.com/docs/python/en/latest/sqlalchemy.html |
5a248a93d3ad-6 | insert two records:
>>> # use the crate engine from earlier examples
>>> Session = sessionmaker(bind=crate)
>>> session = Session()
>>> arthur = Character(name='Arthur Dent')
>>> arthur.details = {}
>>> arthur.details['gender'] = 'male'
>>> arthur.details['species'] = 'human'
>>> session.add(arthur)
>>> trillian = Char... | https://cratedb.com/docs/python/en/latest/sqlalchemy.html |
5a248a93d3ad-7 | >>> session.commit()
The resulting object will look like this:
>>> arthur.more_details
[{'foo': 1, 'bar': 10}, {'foo': 2}, {'foo': 3}]
Caution
Behind the scenes, if you update an ObjectArray, and commit that
change, the UPDATE statement
sent to CrateDB will include all of the ObjectArray data.
Geopoint and Geoshape¶
Th... | https://cratedb.com/docs/python/en/latest/sqlalchemy.html |
5a248a93d3ad-8 | ... (139.584, 35.619),
... (139.806, 35.515),
... ]
... ]
... )
You can then set the values of the Geopoint and Geoshape columns:
>>> tokyo = City(name="Tokyo", coordinate=point, area=area)
>>> session.add(tokyo)
>>> session.commit()
Querying¶
When the commit method is called, two IN... | https://cratedb.com/docs/python/en/latest/sqlalchemy.html |
5a248a93d3ad-9 | >>> from sqlalchemy.sql import operators
>>> query = session.query(Character.name)
>>> query.filter(Character.more_details['foo'].any(1, operator=operators.eq)).all()
[(u'Arthur Dent',)]
Here, we’re using SQLAlchemy’s any
method along with Python’s operator.eq() function, in order to
match the value 1 against the key f... | https://cratedb.com/docs/python/en/latest/sqlalchemy.html |
5a248a93d3ad-10 | ... .group_by(Character.name) \
... .order_by(sa.desc(sa.func.count(Character.id))) \
... .order_by(Character.name).all()
[(1, u'Arthur Dent'), (1, u'Tricia McMillan')]
Fulltext search¶
Matching¶
Fulltext Search in CrateDB is done with the MATCH Predicate.
The CrateDB SQLAlchemy dialect provides a match fun... | https://cratedb.com/docs/python/en/latest/sqlalchemy.html |
5a248a93d3ad-11 | match_type
(optional)
The Match Types.
Determine how the term is applied and the _score gets calculated.
See also score usage.
Here’s an example:
match({Character.name_ft: 0.5,
Character.details['name']['first']: 0.8,
Character.details['name']['last']: 0.2},
'Trillian',
match_type='phrase')
op... | https://cratedb.com/docs/python/en/latest/sqlalchemy.html |
5a248a93d3ad-12 | index. And we’re selecting the name column of the character by using the
table definition But notice that we select the associated score by passing in
the virtual column name as a string (_score) instead of using a defined
column on the Character class. | https://cratedb.com/docs/python/en/latest/sqlalchemy.html |
d88b09dfdf32-0 | Feedback
Suggest improvement
Edit page
View page source
latest
Data types¶
The Database API client and the SQLAlchemy dialect use different Python data types. Consult the corresponding
section for further information.
Table of contents
Database API client
SQLAlche... | https://cratedb.com/docs/python/en/latest/data-types.html |
d88b09dfdf32-1 | CrateDB
SQLAlchemy
boolean
Boolean
byte
SmallInteger
short
SmallInteger
integer
Integer
long
NUMERIC
float
Float
double
DECIMAL
timestamp
TIMESTAMP
string
String
array
ARRAY
object
ObjectType (extension type)
array(object)
ObjectArray (extension type)
geo_point
Geopoint and Geoshape (extension type)
geo_shape
Geopoint ... | https://cratedb.com/docs/python/en/latest/data-types.html |
4ea5d16bed25-0 | Feedback
Suggest improvement
Edit page
View page source
latest
Getting started¶
Learn how to install and get started with the Python client library for
CrateDB.
Table of contents
Install
Interactive use
Set up as a dependency
Next steps
Install¶
The CrateDB Python... | https://cratedb.com/docs/python/en/latest/getting-started.html |
e5d2c5b1d3f3-0 | Feedback
Suggest improvement
Edit page
View page source
latest
Blobs¶
The CrateDB Python client library provides full access to the powerful
blob storage capabilities of your
CrateDB cluster.
Table of contents
Get a blob container
Working with the blob container
U... | https://cratedb.com/docs/python/en/latest/blobs.html |
e5d2c5b1d3f3-1 | The io.StringIO class is not suitable, as it produces Unicode strings when
read. But you can easily encode a Unicode string and feed it to a io.BytesIO
object.
Here’s a trivial example:
>>> import io
>>> bytestream = "An example sentence.".encode("utf8")
>>> file = io.BytesIO(bytestream)
This file can then be uploaded ... | https://cratedb.com/docs/python/en/latest/blobs.html |
e5d2c5b1d3f3-2 | And upload it:
>>> blob_container.put(another_file, digest)
True
The put method returns True, indicating that the object has been
written to the blob container.
Retrieve blobs¶
To retrieve a blob, you need to know its digest.
Let’s use the digest variable we created before to check whether that object
exists with the e... | https://cratedb.com/docs/python/en/latest/blobs.html |
4db4bfa78575-0 | Feedback
Suggest improvement
Edit page
View page source
latest
Query CrateDB¶
Note
This page documents the CrateDB client, implementing the
Python Database API Specification v2.0 (PEP 249).
For help using the SQLAlchemy dialect, consult
the SQLAlchemy dialect docu... | https://cratedb.com/docs/python/en/latest/query.html |
4db4bfa78575-1 | >>> cursor.executemany(
... "INSERT INTO locations (name, date, kind, position) VALUES (?, ?, ?, ?)",
... [('Cloverleaf', '2007-03-11', 'Quasar', 7),
... ('Old Faithful', '2007-03-11', 'Quasar', 7)])
[{'rowcount': 1}, {'rowcount': 1}]
The executemany() method returns a result dictionary
for every tuple. Th... | https://cratedb.com/docs/python/en/latest/query.html |
4db4bfa78575-2 | returns the specified number of result rows:
>>> cursor.execute("SELECT name FROM locations order by name")
>>> result = cursor.fetchmany(2)
>>> pprint(result)
[['Aldebaran'], ['Algol']]
If a number is not given as an argument, fetch_many() will return a result
list with one result row:
>>> cursor.fetchmany()
[['Allosi... | https://cratedb.com/docs/python/en/latest/query.html |
4db4bfa78575-3 | ('description', None, None, None, None, None, None),
...
('nullable_datetime', None, None, None, None, None, None),
('position', None, None, None, None, None, None))
You can turn this into something more manageable with List Comprehensions:
>>> [column[0] for column in cursor.description]
['date', 'datetime_tz', 'dat... | https://cratedb.com/docs/python/en/latest/query.html |
4db4bfa78575-4 | >>> from crate.client.converter import Converter, DataType
>>> converter = Converter()
>>> converter.set(DataType.BOOLEAN, lambda value: value is True and "yes" or "no")
>>> cursor = connection.cursor(converter=converter)
>>> cursor.execute("SELECT flag FROM locations ORDER BY name")
>>> cursor.fetchone()
['no']
TIMEST... | https://cratedb.com/docs/python/en/latest/query.html |
4db4bfa78575-5 | >>> import pytz
>>> cursor.time_zone = pytz.timezone("Australia/Sydney")
>>> cursor.execute("SELECT datetime_tz FROM locations ORDER BY name")
>>> cursor.fetchone()
['foo', datetime.datetime(2022, 7, 19, 4, 10, 36, 758000, tzinfo=<DstTzInfo 'Australia/Sydney' AEST+10:00:00 STD>)]
>>> try:
... import zoneinfo
... ex... | https://cratedb.com/docs/python/en/latest/query.html |
ef2ab7cc6996-0 | Feedback
Suggest improvement
Edit page
View page source
latest
Index | https://cratedb.com/docs/python/en/latest/genindex.html |
f89555a1919d-0 | Feedback
Suggest improvement
latest
Search
From here you can search these documents. Enter your search
words into the box below and click "search". Note that the search
function will automatically search for all of the words. Pages
containing fewer words won't appear in the result li... | https://cratedb.com/docs/python/en/latest/search.html |
fa67928b2e7c-0 | Feedback
Suggest improvement
Edit page
View page source
latest
Connect to CrateDB¶
Note
This page documents the CrateDB client, implementing the
Python Database API Specification v2.0 (PEP 249).
For help using the SQLAlchemy dialect, consult the
SQLAlchemy dialect... | https://cratedb.com/docs/python/en/latest/connect.html |
fa67928b2e7c-1 | i.e. http://localhost:4200/.
If you’re just getting started with CrateDB, the first time you connect,
you can probably omit this argument.
Connect to multiple nodes¶
To connect to one of multiple nodes, pass a list of database URLs to the
connect() function, like so:
>>> connection = client.connect(["<NODE_1_URL>", "<N... | https://cratedb.com/docs/python/en/latest/connect.html |
fa67928b2e7c-2 | >>> connection = client.connect(..., verify_ssl_cert=False)
Client verification¶
The client also supports client verification via client certificates.
Here’s how you might do that:
>>> connection = client.connect(..., cert_file="<CERT_FILE>", key_file="<KEY_FILE>")
Here, replace <CERT_FILE> with the path to the client ... | https://cratedb.com/docs/python/en/latest/connect.html |
fa67928b2e7c-3 | >>> connection = client.connect(..., backoff_factor=0.1)
If backoff_factor is set to 0.1, then the delay between retries will be 0.0,
0.1, 0.2, 0.4 etc. The maximum backoff factor cannot exceed 120 seconds and by
default its value is 0.
Socket Options¶
Creating connections uses urllib3 default socket options but additi... | https://cratedb.com/docs/python/en/latest/connect.html |
fa67928b2e7c-4 | Here, replace <USERNAME> and <PASSWORD> with the appropriate username
and password.
Tip
If you have not configured a custom database user, you probably want to
authenticate as the CrateDB superuser, which is crate. The superuser
does not have a password, so you can omit the password argument.
Schema selection¶
You can ... | https://cratedb.com/docs/python/en/latest/connect.html |
a3106c22dd2c-0 | Feedback
Suggest improvement
Edit page
View page source
latest
Database client¶
crate.client.connect is the primary method to connect to CrateDB using
Python. This section of the documentation outlines different methods to connect
to the database cluster, as well ... | https://cratedb.com/docs/python/en/latest/by-example/client.html |
a3106c22dd2c-1 | >>> connection = client.connect([crate_host], error_trace=True)
>>> connection.close()
It’s possible to define a default timeout value in seconds for all servers
using the optional parameter timeout:
>>> connection = client.connect([crate_host, invalid_host], timeout=5)
>>> connection.close()
Authentication¶
Users that... | https://cratedb.com/docs/python/en/latest/by-example/client.html |
a3106c22dd2c-2 | ... schema='custom_schema')
>>> connection.close()
Inserting Data¶
Use user “crate” for rest of the tests:
>>> connection = client.connect([crate_host])
Before executing any statement, a cursor has to be opened to perform
database operations:
>>> cursor = connection.cursor()
>>> cursor.execu... | https://cratedb.com/docs/python/en/latest/by-example/client.html |
a3106c22dd2c-3 | >>> timestamp_date = "2023-06-26"
>>> datetime_aware = dt.datetime.fromisoformat("2023-06-26T09:24:00.123+02:00")
>>> datetime_naive = dt.datetime.fromisoformat("2023-06-26T09:24:00.123")
>>> datetime_date = dt.date.fromisoformat("2023-06-26")
>>> cursor.execute("UPDATE locations SET date=? WHERE name='Cloverleaf'", (t... | https://cratedb.com/docs/python/en/latest/by-example/client.html |
a3106c22dd2c-4 | >>> pprint(result)
[['Aldebaran'], ['Algol']]
If a size is not given, the cursor’s arraysize, which defaults to ‘1’,
determines the number of rows to be fetched:
>>> cursor.fetchmany()
[['Allosimanius Syneca']]
It’s also possible to change the cursors arraysize to an other value:
>>> cursor.arraysize = 3
>>> cursor.fet... | https://cratedb.com/docs/python/en/latest/by-example/client.html |
a3106c22dd2c-5 | 'Max Quordlepleen claims that the only thing left after the end of the '
'Universe will be the sweets trolley and a fine selection of Aldebaran '
'liqueurs.',
None]
>>> result = cursor.description
>>> pprint(result)
(('name', None, None, None, None, None, None),
('date', None, None, None, None, None, None),
('date... | https://cratedb.com/docs/python/en/latest/by-example/client.html |
a3106c22dd2c-6 | >>> cursor.execute("SELECT * FROM locations")
Traceback (most recent call last):
...
crate.client.exceptions.ProgrammingError: Connection closed
>>> cursor = connection.cursor()
Traceback (most recent call last):
...
crate.client.exceptions.ProgrammingError: Connection closed | https://cratedb.com/docs/python/en/latest/by-example/client.html |
b2286fed88c0-0 | Feedback
Suggest improvement
Edit page
View page source
latest
By example¶
This part of the documentation enumerates different kinds of examples how to
use the CrateDB Python client.
DB API, HTTP, and BLOB interfaces¶
The examples in this section are all about Cra... | https://cratedb.com/docs/python/en/latest/by-example/index.html |
83567cb5e1fe-0 | Feedback
Suggest improvement
Edit page
View page source
latest
HTTPS connection support¶
This documentation section outlines different options to connect to CrateDB
using SSL/TLS.
Table of Contents
Introduction
With certificate verification
Without certificate ver... | https://cratedb.com/docs/python/en/latest/by-example/https.html |
83567cb5e1fe-1 | >>> client.server_infos(crate_host)
Traceback (most recent call last):
...
crate.client.exceptions.ConnectionError: Server not available, ...certificate verify failed...
Without certificate verification¶
When turning off certificate verification, calling the server will succeed,
even when not providing a valid CA certi... | https://cratedb.com/docs/python/en/latest/by-example/https.html |
83567cb5e1fe-2 | >>> client.server_infos(crate_host)
Traceback (most recent call last):
...
crate.client.exceptions.ConnectionError: Server not available, exception: HTTPSConnectionPool...
Relaxing minimum SSL version¶
urrlib3 v2 dropped support for TLS 1.0 and TLS 1.1 by default, see Modern security by default -
HTTPS requires TLS 1.2... | https://cratedb.com/docs/python/en/latest/by-example/https.html |
c8c706a036a7-0 | Feedback
Suggest improvement
Edit page
View page source
latest
HTTP client¶
Table of Contents
Introduction
Server configuration
SQL Statements
Blobs
Error Handling
Introduction¶
The CrateDB Python driver package offers an HTTP client API object.
>>> from crate.cli... | https://cratedb.com/docs/python/en/latest/by-example/http.html |
c8c706a036a7-1 | >>> result = http_client.sql('select name from locations')
>>> http_client._active_servers
['http://127.0.0.1:44209']
Inactive servers will be re-added after a given time interval.
To validate this, set the interval very short and sleep for that interval:
>>> http_client.retry_interval = 1
>>> import time; time.sleep(1... | https://cratedb.com/docs/python/en/latest/by-example/http.html |
c8c706a036a7-2 | ['Galactic Sector QQ7 Active J Gamma'],
['Galaxy'],
['North West Ripple'],
['Outer Eastern Rim']]}
Blobs¶
Check if a blob exists:
>>> http_client.blob_exists('myfiles', '040f06fd774092478d450774f5ba30c5da78acc8')
False
Trying to get a non-existing blob throws an exception:
>>> http_client.... | https://cratedb.com/docs/python/en/latest/by-example/http.html |
c8c706a036a7-3 | True
Blobs are returned as generators, generating a chunk on each call:
>>> g = http_client.blob_get('myfiles', '040f06fd774092478d450774f5ba30c5da78acc8')
>>> print(next(g))
content
The chunk_size can be set explicitly on get:
>>> g = http_client.blob_get(
... 'myfiles', '040f06fd774092478d450774f5ba30c5da78acc8',... | https://cratedb.com/docs/python/en/latest/by-example/http.html |
c8c706a036a7-4 | ... CREATE FUNCTION fib(LONG) RETURNS LONG
... LANGUAGE JAVASCRIPT AS '
... var fib = function fib(n) { return n < 2 ? n : fib(n-1) + fib(n-2); }
... '
... ''')
{...}
>>> http_client.close()
It’s possible to define a HTTP timeout in seconds on client instantiation, so
an exception is raised when the timeout is reache... | https://cratedb.com/docs/python/en/latest/by-example/http.html |
b6479a14d6b8-0 | Feedback
Suggest improvement
Edit page
View page source
latest
The Connection object¶
This documentation section outlines different attributes, methods, and
behaviors of the crate.client.connection.Connection object.
The examples use an instance of ClientMocked in... | https://cratedb.com/docs/python/en/latest/by-example/connection.html |
660bfab6deb9-0 | Feedback
Suggest improvement
Edit page
View page source
latest
Blob container API¶
The connection object provides a convenience API for easy access to
blob tables.
Get blob container handle¶
Create a connection:
>>> from crate.client import connect
>>> client = co... | https://cratedb.com/docs/python/en/latest/by-example/blob.html |
660bfab6deb9-1 | >>> blob_stream = container.get(string_blob)
>>> blob_stream
<generator ...>
>>> data = next(blob_stream)
>>> data == string_data
True
Delete blobs¶
Blobs can be deleted using its hash:
>>> container.delete(string_blob)
True
>>> container.exists(string_blob)
False
Trying to delete a not existing blob:
>>> container.del... | https://cratedb.com/docs/python/en/latest/by-example/blob.html |
b5e180f5cf0d-0 | Feedback
Suggest improvement
Edit page
View page source
latest
The Cursor object¶
This documentation section outlines different attributes, methods, and
behaviors of the crate.client.cursor.Cursor object.
The example code uses ClientMocked and set_next_response fo... | https://cratedb.com/docs/python/en/latest/by-example/cursor.html |
b5e180f5cf0d-1 | >>> cursor.execute('')
>>> cursor.fetchone()
['North West Ripple', 1]
Each call to fetchone() increments the cursor and returns the next row:
>>> cursor.fetchone()
['Arkintoofle Minor', 3]
One more iteration:
>>> cursor.next()
['Alpha Centauri', 3]
The iteration is stopped after the last row is returned.
A further call... | https://cratedb.com/docs/python/en/latest/by-example/cursor.html |
b5e180f5cf0d-2 | [['Alpha Centauri', 3]]
fetchall()¶
fetchall() fetches all (remaining) rows of a query result:
>>> cursor.execute('')
>>> cursor.fetchall()
[['North West Ripple', 1], ['Arkintoofle Minor', 3], ['Alpha Centauri', 3]]
Since all data was fetched ‘None’ is returned by fetchone():
>>> cursor.fetchone()
And each other call r... | https://cratedb.com/docs/python/en/latest/by-example/cursor.html |
b5e180f5cf0d-3 | The rowcount property specifies the number of rows that the last execute() produced:
>>> cursor.execute('')
>>> cursor.rowcount
3
The attribute is -1, in case the cursor has been closed:
>>> cursor.close()
>>> cursor.rowcount
-1
If the last response does not contain the rowcount attribute, -1 is returned:
>>> cursor = ... | https://cratedb.com/docs/python/en/latest/by-example/cursor.html |
b5e180f5cf0d-4 | of parameters:
>>> cursor = connection.cursor()
>>> cursor.executemany('', (1,2,3))
[{'rowcount': 3}, {'rowcount': 2}]
>>> cursor.rowcount
5
>>> cursor.duration
123
executemany() is not intended to be used with statements returning result
sets. The result will always be empty:
>>> cursor.fetchall()
[]
For completeness’... | https://cratedb.com/docs/python/en/latest/by-example/cursor.html |
b5e180f5cf0d-5 | Python data type conversion¶
The cursor object can optionally convert database types to native Python data
types. Currently, this is implemented for the CrateDB data types IP and
TIMESTAMP on behalf of the DefaultTypeConverter.
>>> cursor = connection.cursor(converter=DefaultTypeConverter())
>>> connection.client.set_n... | https://cratedb.com/docs/python/en/latest/by-example/cursor.html |
b5e180f5cf0d-6 | ... "cols":[ "value" ],
... "rowcount":1,
... "duration":123
... })
>>> cursor.execute('')
>>> cursor.fetchone()
[6]
TIMESTAMP conversion with time zone¶
Based on the data type converter functionality, the driver offers a convenient
interface to make it return timezone-aware datetime objects, using the
desi... | https://cratedb.com/docs/python/en/latest/by-example/cursor.html |
b5e180f5cf0d-7 | >>> cursor.time_zone = datetime.timezone.utc
>>> cursor.execute('')
>>> cursor.fetchone()
['foo', datetime.datetime(2022, 7, 18, 18, 10, 36, 758000, tzinfo=datetime.timezone.utc)]
>>> import pytz
>>> cursor.time_zone = pytz.timezone("Australia/Sydney")
>>> cursor.execute('')
>>> cursor.fetchone()
['foo', datetime.datet... | https://cratedb.com/docs/python/en/latest/by-example/cursor.html |
b5ed6362f991-0 | Feedback
Suggest improvement
Edit page
View page source
latest
SQLAlchemy: DataFrame operations¶
Table of Contents
About
Introduction
pandas
Dask
Compatibility notes
Efficient INSERT operations with pandas
Efficient INSERT operations with Dask
About¶
This section ... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/dataframe.html |
b5ed6362f991-1 | and NumPy.
A Dask DataFrame is a large parallel DataFrame composed of many smaller
pandas DataFrames, split along the index. These pandas DataFrames may live on
disk for larger-than-memory computing on a single machine, or on many different
machines in a cluster. One Dask DataFrame operation triggers many operations on... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/dataframe.html |
b5ed6362f991-2 | ... method=insert_bulk,
... )
Tip
You will observe that the optimal chunk size highly depends on the shape of
your data, specifically the width of each record, i.e. the number of columns
and their individual sizes, which will in the end determine the total size of
each batch/chunk.
A few details should be taken int... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/dataframe.html |
b5ed6362f991-3 | then see if performance improves when you increase or decrease that figure.
People are reporting that 10_000-20_000 is their optimal setting, but if you
process, for example, just three “small” columns, you may also experiment with
leveling up to 200_000, because the chunksize should not be too small.
If it is too smal... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/dataframe.html |
b5ed6362f991-4 | >>> CHUNK_SIZE = 25
...
>>> # Create a Dask DataFrame.
>>> df = makeTimeDataFrame(nper=INSERT_RECORDS, freq="S")
>>> ddf = dd.from_pandas(df, npartitions=NPARTITIONS)
...
>>> # Insert content of DataFrame using multiple workers on a
>>> # compute cluster, transferred using batches of records.
>>> ddf.to_sql(
... na... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/dataframe.html |
b5ed6362f991-5 | Adjusting this value in both directions is perfectly fine: If you observe that you are
overloading the machine, maybe because there are workloads scheduled other than the one
you are running, try to reduce the value. If fragments/steps of your implementation
involve waiting for network or disk I/O, you may want to incr... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/dataframe.html |
4353079edd82-0 | Feedback
Suggest improvement
Edit page
View page source
latest
SQLAlchemy: Advanced querying¶
This section of the documentation demonstrates running queries using a fulltext
index with an analyzer, queries using counting and aggregations, and support for
the INSER... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/advanced-querying.html |
4353079edd82-1 | )
We have to create this table using SQL because it is currently not possible to
create INDEX fields using SQLAlchemy’s Declarative Mapping.
However, we can define the table to use all other operations:
>>> def gen_key():
... return str(uuid4())
>>> class Character(Base):
... __tablename__ = 'characters'
... ... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/advanced-querying.html |
4353079edd82-2 | Fulltext search in CrateDB is performed using MATCH Predicate.
The CrateDB SQLAlchemy dialect comes with a match function, which can be used to
search on one or multiple fields.
>>> from crate.client.sqlalchemy.predicates import match
>>> session.query(Character.name) \
... .filter(match(Character.name_ft, 'Arthur'... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/advanced-querying.html |
4353079edd82-3 | function.
>>> session.query(Character.name) \
... .filter(
... match(Character.name_ft, 'Arth',
... match_type='phrase',
... options={'fuzziness': 3})
... ) \
... .all()
[('Arthur Dent',)]
It is not possible to specify options without the match_type argument:
>>> sess... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/advanced-querying.html |
4353079edd82-4 | functionality is supported by the CrateDB client library. Here is an example
that uses insert().from_select().
First, let’s define and create the tables:
>>> from sqlalchemy import select, insert
>>> class Todos(Base):
... __tablename__ = 'todos'
... __table_args__ = {
... 'crate_number_of_replicas': '0... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/advanced-querying.html |
4353079edd82-5 | >>> _ = connection.execute(sa.text("REFRESH TABLE archived_tasks"))
>>> pprint([str(r) for r in session.execute(sa.text("SELECT content FROM archived_tasks"))])
["('Write Tests',)"]
INSERT...RETURNING¶
The RETURNING clause can be used to retrieve the result rows of an INSERT
operation. It may be specified using the Ins... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/advanced-querying.html |
4353079edd82-6 | Insert a user and get the user id:
>>> from sqlalchemy import insert, update
>>> stmt = insert(User).values(username='Arthur Dent', email='arthur_dent@crate.io').returning(User.id, User.username, User.email)
>>> result = session.execute(stmt)
>>> session.commit()
>>> uid = [r[0] for r in result][0]
Now let’s update the... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/advanced-querying.html |
e11a99562036-0 | Feedback
Suggest improvement
Edit page
View page source
latest
SQLAlchemy: Getting started¶
This section of the documentation shows how to connect to CrateDB using its
SQLAlchemy dialect, and how to run basic DDL statements based on an SQLAlchemy
ORM schema defini... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/getting-started.html |
e11a99562036-1 | >>> sa.create_engine('crate://otherserver:4200')
Engine(crate://otherserver:4200)
Multiple Hosts¶
Because CrateDB is a clustered database running on multiple servers, it is
recommended to connect to all of them. This enables the DB-API layer to
use round-robin to distribute the load and skip a server if it becomes
unav... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/getting-started.html |
e11a99562036-2 | 42.42
or use the timeout URL parameter within the database connection URL.
>>> timeout_engine = sa.create_engine('crate://localhost/?timeout=42.42')
>>> timeout_engine.raw_connection().driver_connection.client._pool_kw["timeout"]
42.42
Pool Size¶
In order to configure the database connection pool size, use the pool_siz... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/getting-started.html |
e11a99562036-3 | >>> engine.dialect.has_table(connection, table_name='departments')
False
In order to create all missing tables, the create_all method can be used:
>>> Base.metadata.create_all(bind=engine)
With that, the table has been created:
>>> engine.dialect.has_table(connection, table_name='departments')
True
Let’s also verify th... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/getting-started.html |
81badbc02860-0 | Feedback
Suggest improvement
Edit page
View page source
latest
SQLAlchemy: Database schema inspection and reflection¶
This section shows you how to inspect the schema of a database using CrateDB’s
SQLAlchemy integration.
Introduction¶
The CrateDB SQLAlchemy integr... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/inspection-reflection.html |
81badbc02860-1 | >>> inspector.default_schema_name
'doc'
Schema-supported reflection¶
A Table object can load its own schema information from the corresponding
table in the database. This process is called reflection, see
Reflecting Database Objects.
In the most simple case you need only specify the table name, a MetaData
object, and t... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/inspection-reflection.html |
30a93b70d641-0 | Feedback
Suggest improvement
Edit page
View page source
latest
SQLAlchemy: Create, retrieve, update, and delete¶
This section of the documentation shows how to query, insert, update and delete
records using CrateDB’s SQLAlchemy integration, it includes common scen... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/crud.html |
30a93b70d641-1 | ... details = sa.Column(ObjectArray)
Create an SQLAlchemy Session:
>>> session = sessionmaker(bind=engine)()
Create¶
Insert a new location:
>>> location = Location()
>>> location.name = 'Earth'
>>> location.kind = 'Planet'
>>> location.flag = True
>>> session.add(location)
>>> session.flush()
Refresh “locations” ta... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/crud.html |
30a93b70d641-2 | >>> [l.name for l in locations if l is not None]
['Algol', 'Allosimanius Syneca']
With filter:
>>> location = session.query(Location).filter_by(name='Algol').one()
>>> location.name
'Algol'
Order by:
>>> locations = session.query(Location).filter(Location.name is not None).order_by(sa.desc(Location.name))
>>> locations... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/crud.html |
30a93b70d641-3 | >>> _ = connection.execute(text("REFRESH TABLE locations"))
Update multiple records using SQL:
>>> with engine.begin() as conn:
... result = conn.execute(text("update locations set flag=true where kind='Update'"))
... result.rowcount
10
Update all records using SQL, and check that the number of documents affect... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/crud.html |
30a93b70d641-4 | >>> session.delete(location)
>>> session.commit()
>>> session.flush()
>>> _ = connection.execute(text("REFRESH TABLE locations"))
>>> session.query(Location).count()
23 | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/crud.html |
a8660cce461f-0 | Feedback
Suggest improvement
Edit page
View page source
latest
SQLAlchemy: Working with special CrateDB types¶
This section of the documentation shows how to work with special data types
from the CrateDB SQLAlchemy dialect. Currently, these are:
Container types Ob... | https://cratedb.com/docs/python/en/latest/by-example/sqlalchemy/working-with-types.html |
End of preview. Expand in Data Studio
No dataset card yet
- Downloads last month
- 7