├── .env ├── .flake8 ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE.txt ├── MANIFEST.in ├── README.md ├── RELEASING.md ├── docker-compose.yml ├── es ├── __init__.py ├── baseapi.py ├── basesqlalchemy.py ├── const.py ├── elastic │ ├── __init__.py │ ├── api.py │ └── sqlalchemy.py ├── exceptions.py ├── opendistro │ ├── __init__.py │ ├── api.py │ └── sqlalchemy.py └── tests │ ├── __init__.py │ ├── fixtures │ ├── __init__.py │ ├── data1.json │ ├── data1_mappings.json │ ├── fixtures.py │ └── flights.json │ ├── test_0_fixtures.py │ ├── test_dbapi.py │ └── test_sqlalchemy.py ├── requirements-dev.txt ├── requirements.txt ├── setup.cfg ├── setup.py └── utils └── export.py /.env: -------------------------------------------------------------------------------- 1 | discovery.type=single-node 2 | opendistro_security.disabled:true 3 | # ELASTIC_USERNAME=elastic 4 | # ELASTIC_PASSWORD=PleaseChangeMe 5 | # xpack.security.enabled=true 6 | # xpack.license.self_generated.type=trial 7 | 8 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | import-order-style = google 3 | max-line-length = 90 4 | exclude = .tox,site-packages,build,dist,.idea,es_dbapi.egg-info 5 | ignore = C812,C813,W503,C816 6 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # Python unit tests 2 | name: Python 3 | 4 | on: 5 | push: 6 | branches: ['master'] 7 | pull_request: 8 | branches: ['master'] 9 | 10 | jobs: 11 | lint: 12 | runs-on: ubuntu-22.04 13 | strategy: 14 | matrix: 15 | python-version: [3.7] 16 | steps: 17 | - name: Checkout code 18 | uses: actions/checkout@v2 19 | - name: Setup Python 20 | uses: actions/setup-python@v2 21 | with: 22 | python-version: ${{ matrix.python-version }} 23 | - name: Install dependencies 24 | run: | 25 | pip install --upgrade pip 26 | pip install -r requirements.txt 27 | pip install -r requirements-dev.txt 28 | - name: black 29 | run: black --check setup.py es 30 | - name: flake8 31 | run: flake8 es 32 | - name: mypy 33 | run: mypy es 34 | 35 | tests: 36 | runs-on: ubuntu-22.04 37 | strategy: 38 | matrix: 39 | python-version: [3.7, 3.8, 3.9] 40 | services: 41 | elasticsearch: 42 | image: elasticsearch:7.3.2 43 | env: 44 | discovery.type: single-node 45 | ports: 46 | - 9200:9200 47 | opendistro: 48 | image: amazon/opendistro-for-elasticsearch:1.12.0 49 | env: 50 | discovery.type: single-node 51 | ports: 52 | - 19200:9200 53 | opendistro_new: 54 | image: amazon/opendistro-for-elasticsearch:1.13.0 55 | env: 56 | discovery.type: single-node 57 | ports: 58 | - 29200:9200 59 | elasticsearch_7_10: 60 | image: elasticsearch:7.10.1 61 | env: 62 | discovery.type: single-node 63 | ports: 64 | - 39200:9200 65 | elasticsearch_7_16: 66 | image: elasticsearch:7.16.1 67 | env: 68 | discovery.type: single-node 69 | ports: 70 | - 49200:9200 71 | 72 | steps: 73 | - uses: actions/checkout@v2 74 | - name: Setup Python 75 | uses: actions/setup-python@v2 76 | with: 77 | python-version: ${{ matrix.python-version }} 78 | - name: Install dependencies 79 | run: | 80 | pip install --upgrade pip 81 | pip install -r requirements.txt 82 | pip install -r requirements-dev.txt 83 | pip install -e . 84 | - name: Run tests on Elasticsearch 85 | run: | 86 | export ES_URI="http://localhost:9200" 87 | export ES_PORT=9200 88 | export ES_SUPPORT_DATETIME_PARSE=False 89 | nosetests -v --with-coverage --cover-package=es es.tests 90 | - name: Run tests on Elasticsearch 7.10.X 91 | run: | 92 | export ES_URI="http://localhost:39200" 93 | export ES_PORT=39200 94 | nosetests -v --with-coverage --cover-package=es es.tests 95 | - name: Run tests on Elasticsearch 7.16.X 96 | run: | 97 | export ES_URI="http://localhost:49200" 98 | export ES_PORT=49200 99 | nosetests -v --with-coverage --cover-package=es es.tests 100 | - name: Run tests on Opendistro 101 | run: | 102 | export ES_DRIVER=odelasticsearch 103 | export ES_URI="https://admin:admin@localhost:19200" 104 | export ES_PASSWORD=admin 105 | export ES_PORT=19200 106 | export ES_SCHEME=https 107 | export ES_USER=admin 108 | export ES_SUPPORT_DATETIME_PARSE=False 109 | nosetests -v --with-coverage --cover-package=es es.tests 110 | - name: Run tests on Opendistro 13 111 | run: | 112 | export ES_DRIVER=odelasticsearch 113 | export ES_URI="https://admin:admin@localhost:29200" 114 | export ES_PASSWORD=admin 115 | export ES_PORT=29200 116 | export ES_SCHEME=https 117 | export ES_USER=admin 118 | export ES_V2=True 119 | export ES_SUPPORT_DATETIME_PARSE=False 120 | nosetests -v --with-coverage --cover-package=es es.tests 121 | - name: Upload code coverage 122 | run: | 123 | bash <(curl -s https://codecov.io/bash) -cF python 124 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .coverage 2 | coverage.xml 3 | *.egg-info 4 | .eggs/ 5 | *.pyc 6 | app.db 7 | ./tmp 8 | build/ 9 | dist/ 10 | docs/_build/ 11 | .idea 12 | .idea/ 13 | env 14 | venv 15 | *.sublime* 16 | .vscode/ 17 | .tox 18 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## Change log 2 | 3 | ### 0.2.11 4 | 5 | - fix: relax packaging dependency (#109) [Daniel Vaz Gaspar] 6 | 7 | ### 0.2.10 8 | 9 | - fix: OpenDistro dialect quotes properly with backticks now (#99) [Beto Dealmeida] 10 | 11 | ### 0.2.9 12 | 13 | - fix: remove six dependency (#84) [Daniel Vaz Gaspar] 14 | 15 | ### 0.2.8 16 | 17 | - fix: remove show tables column retrieval index based (#81) [Daniel Vaz Gaspar] 18 | 19 | ### 0.2.7 20 | 21 | - fix: unpin packaging dependency (#77) [Daniel Vaz Gaspar] 22 | 23 | ### 0.2.6 24 | 25 | - fix: pin elasticsearch-py bellow 7.14 (#71) [Daniel Vaz Gaspar] 26 | - feat(query): add time_zone param (#69) [aniaan] 27 | 28 | ### 0.2.5 29 | 30 | - fix: Bump packaging [Beto Dealmeida] 31 | 32 | ### 0.2.4 33 | 34 | - fix: Bump urllib3 from 1.25.6 to 1.26.5 (#64) [dependabot] 35 | - fix: missing time type (#60) [maltoze] 36 | 37 | ### 0.2.3 38 | 39 | - fix: missing dependency, packaging [Daniel Vaz Gaspar] 40 | 41 | ### 0.2.2 42 | 43 | - fix: support elasticsearch > 7.10 [Daniel Vaz Gaspar] 44 | 45 | ### 0.2.1 46 | 47 | - feat: support new opendistro SQL engine 1.13 [Daniel Vaz Gaspar] 48 | 49 | ### 0.2.0 50 | 51 | - docs: update changelog [Daniel Vaz Gaspar] 52 | - release: version bump and exception fix (#48) [Daniel Vaz Gaspar] 53 | - feat(opendistro): implement get view names with ES alias (#47) [Daniel Vaz Gaspar] 54 | - fix(opendistro): aws auth and discard not supported engine type from meta (#46) [Daniel Vaz Gaspar] 55 | - feat: support opendistro (#45) [Daniel Vaz Gaspar] 56 | 57 | ### 0.1.4 58 | 59 | - [fix]: crash with empty indexes (#39) [Daniel Vaz Gaspar] 60 | - [docs]: update README with github actions badge (#41) [Daniel Vaz Gaspar] 61 | - [ci]: from travis to github actions (#40) [Daniel Vaz Gaspar] 62 | - [docs]: updated readme opendistro info (#37) [Anirudha (Ani) Jadhav] 63 | 64 | ### 0.1.3 65 | 66 | - [elasticsearch]: feat: `fetch_size` configurable and set default to 10000 (#30) 67 | - [docs]: fix: Update README.md (#32) 68 | 69 | ### 0.1.2 70 | 71 | - [elasticsearch] fix: newer elasticsearch version were crashing (#23) 72 | 73 | ### 0.1.1 74 | 75 | - [dbapi] fix: enforce list tuple to follow PEP-249 (#17) 76 | - [dbapi] fix: don't do anything in commit method (#16) 77 | - [dbapi] fix: support connection string without trailing slash (#9) 78 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2019] [Preset Inc] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | prune *.pyc 2 | include LICENSE.txt 3 | include README.md 4 | recursive-include es/ * 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ElasticSearch DBAPI 2 | 3 | 4 | [![Build Status](https://github.com/preset-io/elasticsearch-dbapi/workflows/Python/badge.svg)](https://github.com/preset-io/elasticsearch-dbapi/actions) 5 | [![PyPI version](https://badge.fury.io/py/elasticsearch-dbapi.svg)](https://badge.fury.io/py/elasticsearch-dbapi) 6 | [![Coverage Status](https://codecov.io/github/preset-io/elasticsearch-dbapi/coverage.svg?branch=master)](https://codecov.io/github/preset-io/elasticsearch-dbapi) 7 | 8 | 9 | `elasticsearch-dbapi` Implements a DBAPI (PEP-249) and SQLAlchemy dialect, 10 | that enables SQL access on elasticsearch clusters for query only access. 11 | 12 | On Elastic Elasticsearch: 13 | Uses Elastic X-Pack [SQL API](https://www.elastic.co/guide/en/elasticsearch/reference/current/xpack-sql.html) 14 | 15 | On AWS ES, opendistro Elasticsearch: 16 | [Open Distro SQL](https://opendistro.github.io/for-elasticsearch-docs/docs/sql/) 17 | 18 | This library supports Elasticsearch 7.X versions. 19 | 20 | ### Installation 21 | 22 | ```bash 23 | $ pip install elasticsearch-dbapi 24 | ``` 25 | 26 | To install support for AWS Elasticsearch Service / [Open Distro](https://opendistro.github.io/for-elasticsearch/features/SQL%20Support.html): 27 | 28 | ```bash 29 | $ pip install elasticsearch-dbapi[opendistro] 30 | ``` 31 | 32 | ### Usage: 33 | 34 | #### Using DBAPI: 35 | 36 | ```python 37 | from es.elastic.api import connect 38 | 39 | conn = connect(host='localhost') 40 | curs = conn.cursor() 41 | curs.execute( 42 | "select * from flights LIMIT 10" 43 | ) 44 | print([row for row in curs]) 45 | ``` 46 | 47 | #### Using SQLAlchemy execute: 48 | 49 | ```python 50 | from sqlalchemy.engine import create_engine 51 | 52 | engine = create_engine("elasticsearch+http://localhost:9200/") 53 | rows = engine.connect().execute( 54 | "select * from flights LIMIT 10" 55 | ) 56 | print([row for row in rows]) 57 | ``` 58 | 59 | #### Using SQLAlchemy: 60 | 61 | ```python 62 | from sqlalchemy import func, select 63 | from sqlalchemy.engine import create_engine 64 | from sqlalchemy.schema import MetaData, Table 65 | 66 | 67 | engine = create_engine("elasticsearch+http://localhost:9200/") 68 | logs = Table("flights", MetaData(bind=engine), autoload=True) 69 | count = select([func.count("*")], from_obj=logs).scalar() 70 | print(f"COUNT: {count}") 71 | ``` 72 | 73 | #### Using SQLAlchemy reflection: 74 | 75 | ```python 76 | 77 | from sqlalchemy.engine import create_engine 78 | from sqlalchemy.schema import Table, MetaData 79 | 80 | engine = create_engine("elasticsearch+http://localhost:9200/") 81 | logs = Table("flights", MetaData(bind=engine), autoload=True) 82 | print(engine.table_names()) 83 | 84 | metadata = MetaData() 85 | metadata.reflect(bind=engine) 86 | print([table for table in metadata.sorted_tables]) 87 | print(logs.columns) 88 | ``` 89 | 90 | #### Connection Parameters: 91 | 92 | [elasticsearch-py](https://elasticsearch-py.readthedocs.io/en/master/index.html) 93 | is used to establish connections and transport, this is the official 94 | elastic python library. `Elasticsearch` constructor accepts multiple optional parameters 95 | that can be used to properly configure your connection on aspects like security, performance 96 | and high availability. These optional parameters can be set at the connection string, for 97 | example: 98 | 99 | ```bash 100 | elasticsearch+http://localhost:9200/?http_compress=True&timeout=100 101 | ``` 102 | will set transport to use gzip (http_compress) and timeout to 10 seconds. 103 | 104 | For more information on configuration options, look at `elasticsearch-py`’s documentation: 105 | - [Transport Options](https://elasticsearch-py.readthedocs.io/en/master/connection.html#transport) 106 | - [HTTP tranport](https://elasticsearch-py.readthedocs.io/en/master/transports.html#urllib3httpconnection) 107 | 108 | The connection string follows RFC-1738, to support multiple nodes you should use `sniff_*` parameters 109 | 110 | #### Fetch size 111 | 112 | By default the maximum number of rows which get fetched by a single query 113 | is limited to 10000. This can be adapted through the `fetch_size` 114 | parameter: 115 | 116 | ```python 117 | from es.elastic.api import connect 118 | 119 | conn = connect(host="localhost", fetch_size=1000) 120 | curs = conn.cursor() 121 | ``` 122 | 123 | If more than 10000 rows should get fetched then 124 | [max_result_window](https://www.elastic.co/guide/en/elasticsearch/reference/7.x/index-modules.html#dynamic-index-settings) 125 | has to be adapted as well. 126 | 127 | #### Time zone 128 | 129 | By default, elasticsearch query time zone defaults to `Z` (UTC). This can be adapted through the `time_zone` 130 | parameter: 131 | 132 | ```python 133 | from es.elastic.api import connect 134 | 135 | conn = connect(host="localhost", time_zone="Asia/Shanghai") 136 | curs = conn.cursor() 137 | ``` 138 | 139 | ### Tests 140 | 141 | To run unittest launch elasticsearch and kibana (kibana is really not required but is a nice to have) 142 | 143 | ```bash 144 | $ docker-compose up -d 145 | $ nosetests -v 146 | ``` 147 | 148 | ### Special case for sql opendistro endpoint (AWS ES) 149 | 150 | AWS ES exposes the opendistro SQL plugin, and it follows a different SQL dialect. 151 | Using the `odelasticsearch` driver: 152 | 153 | ```python 154 | from sqlalchemy.engine import create_engine 155 | 156 | engine = create_engine( 157 | "odelasticsearch+https://search-SOME-CLUSTER.us-west-2.es.amazonaws.com:443/" 158 | ) 159 | rows = engine.connect().execute( 160 | "select count(*), Carrier from flights GROUP BY Carrier" 161 | ) 162 | print([row for row in rows]) 163 | ``` 164 | 165 | Or using DBAPI: 166 | ```python 167 | from es.opendistro.api import connect 168 | 169 | conn = connect(host='localhost',port=9200,path="", scheme="http") 170 | 171 | curs = conn.cursor().execute( 172 | "select * from flights LIMIT 10" 173 | ) 174 | 175 | print([row for row in curs]) 176 | ``` 177 | 178 | ### Opendistro (AWS ES) Basic authentication 179 | 180 | Basic authentication is configured as expected on the , fields of the URI 181 | 182 | ```python 183 | from sqlalchemy.engine import create_engine 184 | 185 | engine = create_engine( 186 | "odelasticsearch+https://my_user:my_password@search-SOME-CLUSTER.us-west-2.es.amazonaws.com:443/" 187 | ) 188 | ``` 189 | 190 | IAM AWS Authentication keys are passed on the URI basic auth location, and by setting `aws_keys` 191 | 192 | Query string keys are: 193 | 194 | - aws_keys 195 | - aws_region 196 | 197 | ```python 198 | from sqlalchemy.engine import create_engine 199 | 200 | engine = create_engine( 201 | "odelasticsearch+https://:@search-SOME-CLUSTER.us-west-2.es.amazonaws.com:443/?aws_keys=1&&aws_region=" 202 | ) 203 | ``` 204 | 205 | IAM AWS profile is configured has a query parameter name `aws_profile` on the URI. The value for the key provides the AWS region 206 | 207 | ```python 208 | from sqlalchemy.engine import create_engine 209 | 210 | engine = create_engine( 211 | "odelasticsearch+https://search-SOME-CLUSTER.us-west-2.es.amazonaws.com:443/?aws_profile=us-west-2" 212 | ) 213 | ``` 214 | 215 | Using the new SQL engine: 216 | 217 | Opendistro 1.13.0 brings (enabled by default) a new SQL engine, with lots of improvements and fixes. 218 | Take a look at the [release notes](https://github.com/opendistro-for-elasticsearch/sql/blob/develop/docs/dev/NewSQLEngine.md) 219 | 220 | This DBAPI has to behave slightly different for SQL v1 and SQL v2, by default we comply with v1, 221 | to enable v2 support, pass `v2=true` has a query parameter. 222 | 223 | ``` 224 | odelasticsearch+https://search-SOME-CLUSTER.us-west-2.es.amazonaws.com:443/?aws_profile=us-west-2&v2=true 225 | ``` 226 | 227 | To connect to the provided Opendistro ES on `docker-compose` use the following URI: 228 | `odelasticsearch+https://admin:admin@localhost:9400/?verify_certs=False` 229 | 230 | ### Known limitations 231 | 232 | This library does not yet support the following features: 233 | 234 | - Array type columns are not supported. Elaticsearch SQL does not support them either. 235 | SQLAlchemy `get_columns` will exclude them. 236 | - `object` and `nested` column types are not well supported and are converted to strings 237 | - Indexes that whose name start with `.` 238 | - GEO points are not currently well-supported and are converted to strings 239 | 240 | - AWS ES (opendistro elascticsearch) is supported (still beta), known limitations are: 241 | * You are only able to `GROUP BY` keyword fields (new [experimental](https://github.com/opendistro-for-elasticsearch/sql#experimental) 242 | opendistro SQL already supports it) 243 | * Indices with dots are not supported (indices like 'audit_log.2021.01.20'), 244 | on these cases we recommend the use of aliases 245 | -------------------------------------------------------------------------------- /RELEASING.md: -------------------------------------------------------------------------------- 1 | 2 | - Create new branch and PR named: `release/X.Y.Z`. 3 | - Update `setup.py` and CHANGELOG.md. 4 | - Let CI run and be green, then merge. 5 | - Release to Pypi 6 | 7 | ``` bash 8 | python setup.py sdist bdist_wheel 9 | twine upload dist/* 10 | ``` 11 | - tag X.Y.Z 12 | - Create github release 13 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | services: 3 | elasticsearch: 4 | image: elasticsearch:7.10.1 5 | env_file: .env 6 | ports: 7 | - 9200:9200 8 | - 9300:9300 9 | 10 | opendistro: 11 | image: amazon/opendistro-for-elasticsearch:1.12.0 12 | env_file: .env 13 | ports: 14 | - 19200:9200 15 | - 19300:9300 16 | 17 | opendistro_13: 18 | image: amazon/opendistro-for-elasticsearch:1.13.0 19 | env_file: .env 20 | ports: 21 | - 29200:9200 22 | - 29300:9300 23 | 24 | kibana: 25 | image: docker.elastic.co/kibana/kibana:7.10.1 26 | env_file: .env 27 | ports: 28 | - 5601:5601 29 | 30 | -------------------------------------------------------------------------------- /es/__init__.py: -------------------------------------------------------------------------------- 1 | from es.elastic.api import connect 2 | from es.exceptions import ( 3 | DatabaseError, 4 | DataError, 5 | Error, 6 | IntegrityError, 7 | InterfaceError, 8 | InternalError, 9 | NotSupportedError, 10 | OperationalError, 11 | ProgrammingError, 12 | Warning, 13 | ) 14 | 15 | 16 | __all__ = [ 17 | "connect", 18 | "apilevel", 19 | "threadsafety", 20 | "paramstyle", 21 | "DataError", 22 | "DatabaseError", 23 | "Error", 24 | "IntegrityError", 25 | "InterfaceError", 26 | "InternalError", 27 | "NotSupportedError", 28 | "OperationalError", 29 | "ProgrammingError", 30 | "Warning", 31 | ] 32 | 33 | 34 | apilevel = "2.0" 35 | # Threads may share the module and connections 36 | threadsafety = 2 37 | paramstyle = "pyformat" 38 | -------------------------------------------------------------------------------- /es/baseapi.py: -------------------------------------------------------------------------------- 1 | from collections import namedtuple 2 | from typing import Any, Dict, List, Optional, Tuple 3 | from urllib import parse 4 | 5 | from elasticsearch import Elasticsearch 6 | from elasticsearch import exceptions as es_exceptions 7 | from es import exceptions 8 | 9 | 10 | from .const import DEFAULT_FETCH_SIZE, DEFAULT_SCHEMA, DEFAULT_SQL_PATH 11 | 12 | 13 | CursorDescriptionRow = namedtuple( 14 | "CursorDescriptionRow", 15 | ["name", "type", "display_size", "internal_size", "precision", "scale", "null_ok"], 16 | ) 17 | 18 | CursorDescriptionType = List[CursorDescriptionRow] 19 | 20 | 21 | class Type(object): 22 | STRING = 1 23 | NUMBER = 2 24 | BOOLEAN = 3 25 | DATETIME = 4 26 | 27 | 28 | def check_closed(f): 29 | """Decorator that checks if connection/cursor is closed.""" 30 | 31 | def wrap(self, *args, **kwargs): 32 | if self.closed: 33 | raise exceptions.Error( 34 | "{klass} already closed".format(klass=self.__class__.__name__) 35 | ) 36 | return f(self, *args, **kwargs) 37 | 38 | return wrap 39 | 40 | 41 | def check_result(f): 42 | """Decorator that checks if the cursor has results from `execute`.""" 43 | 44 | def wrap(self, *args, **kwargs): 45 | if self._results is None: 46 | raise exceptions.Error("Called before `execute`") 47 | return f(self, *args, **kwargs) 48 | 49 | return wrap 50 | 51 | 52 | def get_type(data_type) -> int: 53 | type_map = { 54 | "text": Type.STRING, 55 | "keyword": Type.STRING, 56 | "integer": Type.NUMBER, 57 | "half_float": Type.NUMBER, 58 | "scaled_float": Type.NUMBER, 59 | "geo_point": Type.STRING, 60 | # TODO get a solution for nested type 61 | "nested": Type.STRING, 62 | "object": Type.STRING, 63 | "date": Type.DATETIME, 64 | "datetime": Type.DATETIME, 65 | "timestamp": Type.DATETIME, 66 | "short": Type.NUMBER, 67 | "long": Type.NUMBER, 68 | "float": Type.NUMBER, 69 | "double": Type.NUMBER, 70 | "bytes": Type.NUMBER, 71 | "boolean": Type.BOOLEAN, 72 | "ip": Type.STRING, 73 | "interval_minute_to_second": Type.STRING, 74 | "interval_hour_to_second": Type.STRING, 75 | "interval_hour_to_minute": Type.STRING, 76 | "interval_day_to_second": Type.STRING, 77 | "interval_day_to_minute": Type.STRING, 78 | "interval_day_to_hour": Type.STRING, 79 | "interval_year_to_month": Type.STRING, 80 | "interval_second": Type.STRING, 81 | "interval_minute": Type.STRING, 82 | "interval_day": Type.STRING, 83 | "interval_month": Type.STRING, 84 | "interval_year": Type.STRING, 85 | "time": Type.STRING, 86 | } 87 | return type_map[data_type.lower()] 88 | 89 | 90 | def get_description_from_columns( 91 | columns: List[Dict[str, str]] 92 | ) -> CursorDescriptionType: 93 | return [ 94 | ( 95 | CursorDescriptionRow( 96 | column.get("name") if not column.get("alias") else column.get("alias"), 97 | get_type(column.get("type")), 98 | None, # [display_size] 99 | None, # [internal_size] 100 | None, # [precision] 101 | None, # [scale] 102 | True, # [null_ok] 103 | ) 104 | ) 105 | for column in columns 106 | ] 107 | 108 | 109 | class BaseConnection(object): 110 | 111 | """Connection to an ES Cluster""" 112 | 113 | def __init__( 114 | self, 115 | host: str = "localhost", 116 | port: int = 9200, 117 | path: str = "", 118 | scheme: str = "http", 119 | user: Optional[str] = None, 120 | password: Optional[str] = None, 121 | context: Optional[Dict[Any, Any]] = None, 122 | **kwargs: Any, 123 | ): 124 | netloc = f"{host}:{port}" 125 | path = path or "/" 126 | self.url = parse.urlunparse((scheme, netloc, path, None, None, None)) 127 | self.context = context or {} 128 | self.closed = False 129 | self.cursors: List[BaseCursor] = [] 130 | self.kwargs = kwargs 131 | # Subclass needs to initialize Elasticsearch 132 | self.es: Optional[Elasticsearch] = None 133 | 134 | @check_closed 135 | def close(self): 136 | """Close the connection now.""" 137 | self.closed = True 138 | for cursor in self.cursors: 139 | try: 140 | cursor.close() 141 | except exceptions.Error: 142 | pass # already closed 143 | 144 | @check_closed 145 | def commit(self): 146 | """ 147 | Elasticsearch doesn't support transactions. 148 | 149 | So just do nothing to support this method. 150 | """ 151 | pass 152 | 153 | @check_closed 154 | def cursor(self): 155 | raise NotImplementedError # pragma: no cover 156 | 157 | @check_closed 158 | def execute(self, operation, parameters=None): 159 | cursor = self.cursor() 160 | return cursor.execute(operation, parameters) 161 | 162 | def __enter__(self): 163 | return self.cursor() 164 | 165 | def __exit__(self, *exc): 166 | self.close() 167 | 168 | 169 | class BaseCursor: 170 | """Connection cursor.""" 171 | 172 | custom_sql_to_method: Dict[str, str] = {} 173 | """ 174 | Each child implements custom SQL commands so that we can 175 | add extra missing logic or restrictions. 176 | Maps custom SQL to class methods, cursor execute calls a dispatcher 177 | based on this mapping. 178 | """ 179 | 180 | def __init__(self, url: str, es: Elasticsearch, **kwargs): 181 | """ 182 | Base cursor constructor initializes common properties 183 | that are shared by opendistro and elastic. Child just 184 | override the sql_path since they differ on each distribution 185 | 186 | :param url: The connection URL 187 | :param es: An initialized Elasticsearch object 188 | :param kwargs: connection string query arguments 189 | """ 190 | self.url = url 191 | self.es = es 192 | self.sql_path = kwargs.get("sql_path", DEFAULT_SQL_PATH) 193 | self.fetch_size = kwargs.get("fetch_size", DEFAULT_FETCH_SIZE) 194 | self.time_zone: Optional[str] = kwargs.get("time_zone") 195 | # This read/write attribute specifies the number of rows to fetch at a 196 | # time with .fetchmany(). It defaults to 1 meaning to fetch a single 197 | # row at a time. 198 | self.arraysize = 1 199 | 200 | self.closed = False 201 | 202 | # this is updated after a query 203 | self.description: CursorDescriptionType = [] 204 | 205 | # this is set to an iterator after a successful query 206 | self._results: List[Tuple[Any, ...]] = [] 207 | 208 | def custom_sql_to_method_dispatcher(self, command: str) -> Optional["BaseCursor"]: 209 | """ 210 | Generic CUSTOM SQL dispatcher for internal methods 211 | :param command: str 212 | :return: None if no command found, or a Cursor with the result 213 | """ 214 | method_name = self.custom_sql_to_method.get(command.lower()) 215 | return getattr(self, method_name)() if method_name else None 216 | 217 | @property # type: ignore 218 | @check_result 219 | @check_closed 220 | def rowcount(self) -> int: 221 | """Counts the number of rows on a result""" 222 | if self._results: 223 | return len(self._results) 224 | return 0 225 | 226 | @check_closed 227 | def close(self) -> None: 228 | """Close the cursor.""" 229 | self.closed = True 230 | 231 | @check_closed 232 | def execute(self, operation, parameters=None) -> "BaseCursor": 233 | """Children must implement their own custom execute""" 234 | raise NotImplementedError # pragma: no cover 235 | 236 | @check_closed 237 | def executemany(self, operation, seq_of_parameters=None): 238 | raise exceptions.NotSupportedError( 239 | "`executemany` is not supported, use `execute` instead" 240 | ) 241 | 242 | @check_result 243 | @check_closed 244 | def fetchone(self) -> Optional[Tuple[Any, ...]]: 245 | """ 246 | Fetch the next row of a query result set, returning a single sequence, 247 | or `None` when no more data is available. 248 | """ 249 | try: 250 | return self._results.pop(0) 251 | except IndexError: 252 | return None 253 | 254 | @check_result 255 | @check_closed 256 | def fetchmany(self, size: Optional[int] = None) -> List[Tuple[Any, ...]]: 257 | """ 258 | Fetch the next set of rows of a query result, returning a sequence of 259 | sequences (e.g. a list of tuples). An empty sequence is returned when 260 | no more rows are available. 261 | """ 262 | size = size or self.arraysize 263 | output, self._results = self._results[:size], self._results[size:] 264 | return output 265 | 266 | @check_result 267 | @check_closed 268 | def fetchall(self) -> List[Tuple[Any, ...]]: 269 | """ 270 | Fetch all (remaining) rows of a query result, returning them as a 271 | sequence of sequences (e.g. a list of tuples). Note that the cursor's 272 | arraysize attribute can affect the performance of this operation. 273 | """ 274 | return list(self) 275 | 276 | @check_closed 277 | def setinputsizes(self, sizes): # pragma: no cover 278 | # not supported 279 | pass 280 | 281 | @check_closed 282 | def setoutputsizes(self, sizes): # pragma: no cover 283 | # not supported 284 | pass 285 | 286 | @check_closed 287 | def __iter__(self): 288 | return self 289 | 290 | @check_closed 291 | def __next__(self): 292 | output = self.fetchone() 293 | if output is None: 294 | raise StopIteration 295 | return output 296 | 297 | next = __next__ 298 | 299 | def sanitize_query(self, query: str) -> str: 300 | """ 301 | Removes dummy schema from queries 302 | """ 303 | return query.replace(f'FROM "{DEFAULT_SCHEMA}".', "FROM ") 304 | 305 | def elastic_query(self, query: str) -> Dict[str, Any]: 306 | """ 307 | Request an http SQL query to elasticsearch 308 | """ 309 | # Sanitize query 310 | query = self.sanitize_query(query) 311 | payload = {"query": query} 312 | if self.fetch_size is not None: 313 | payload["fetch_size"] = self.fetch_size 314 | if self.time_zone is not None: 315 | payload["time_zone"] = self.time_zone 316 | path = f"/{self.sql_path}/" 317 | try: 318 | response = self.es.transport.perform_request("POST", path, body=payload) 319 | except es_exceptions.ConnectionError: 320 | raise exceptions.OperationalError("Error connecting to Elasticsearch") 321 | except es_exceptions.RequestError as ex: 322 | raise exceptions.ProgrammingError(f"Error ({ex.error}): {ex.info}") 323 | # When method is HEAD and code is 404 perform request returns True 324 | # So response is Union[bool, Any] 325 | if isinstance(response, bool): 326 | raise exceptions.UnexpectedRequestResponse() 327 | # Opendistro errors are http status 200 328 | if "error" in response: 329 | raise exceptions.ProgrammingError( 330 | f"({response['error']['reason']}): {response['error']['details']}" 331 | ) 332 | return response 333 | 334 | 335 | def apply_parameters(operation: str, parameters: Optional[Dict[str, Any]]) -> str: 336 | if parameters is None: 337 | return operation 338 | 339 | escaped_parameters = {key: escape(value) for key, value in parameters.items()} 340 | return operation % escaped_parameters 341 | 342 | 343 | def escape(value): 344 | if value == "*": 345 | return value 346 | elif isinstance(value, str): 347 | return "'{}'".format(value.replace("'", "''")) 348 | elif isinstance(value, bool): 349 | return "TRUE" if value else "FALSE" 350 | elif isinstance(value, (int, float)): 351 | return value 352 | elif isinstance(value, (list, tuple)): 353 | return ", ".join(escape(element) for element in value) 354 | -------------------------------------------------------------------------------- /es/basesqlalchemy.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from __future__ import division 3 | from __future__ import print_function 4 | from __future__ import unicode_literals 5 | 6 | import logging 7 | from typing import Any, List, Type 8 | 9 | import es 10 | from es import exceptions 11 | from es.const import DEFAULT_SCHEMA 12 | from sqlalchemy import types 13 | from sqlalchemy.engine import default 14 | from sqlalchemy.sql import compiler 15 | 16 | 17 | logger = logging.getLogger(__name__) 18 | 19 | 20 | def parse_bool_argument(value: str) -> bool: 21 | if value in ("True", "true"): 22 | return True 23 | elif value in ("False", "false"): 24 | return False 25 | else: 26 | raise ValueError(f"Expected boolean found {value}") 27 | 28 | 29 | class BaseESCompiler(compiler.SQLCompiler): 30 | def visit_fromclause(self, fromclause: str, **kwargs: Any): 31 | return fromclause.replace("default.", "") 32 | 33 | def visit_label(self, *args, **kwargs): 34 | if len(kwargs) == 0 or len(kwargs) == 1: 35 | kwargs["render_label_as_label"] = args[0] 36 | result = super().visit_label(*args, **kwargs) 37 | return result 38 | 39 | 40 | class BaseESTypeCompiler(compiler.GenericTypeCompiler): 41 | def visit_REAL(self, type_, **kwargs: Any) -> str: 42 | return "DOUBLE" 43 | 44 | def visit_NUMERIC(self, type_, **kwargs: Any) -> str: 45 | return "LONG" 46 | 47 | visit_DECIMAL = visit_NUMERIC 48 | visit_INTEGER = visit_NUMERIC 49 | visit_SMALLINT = visit_NUMERIC 50 | visit_BIGINT = visit_NUMERIC 51 | visit_BOOLEAN = visit_NUMERIC 52 | visit_TIMESTAMP = visit_NUMERIC 53 | visit_DATE = visit_NUMERIC 54 | 55 | def visit_CHAR(self, type_, **kwargs: Any) -> str: 56 | return "STRING" 57 | 58 | visit_NCHAR = visit_CHAR 59 | visit_VARCHAR = visit_CHAR 60 | visit_NVARCHAR = visit_CHAR 61 | visit_TEXT = visit_CHAR 62 | 63 | def visit_DATETIME(self, type_, **kwargs: Any) -> str: 64 | return "DATETIME" 65 | 66 | def visit_TIME(self, type_, **kwargs: Any) -> str: 67 | raise exceptions.NotSupportedError("Type TIME is not supported") 68 | 69 | def visit_BINARY(self, type_, **kwargs: Any) -> str: 70 | raise exceptions.NotSupportedError("Type BINARY is not supported") 71 | 72 | def visit_VARBINARY(self, type_, **kwargs: Any) -> str: 73 | raise exceptions.NotSupportedError("Type VARBINARY is not supported") 74 | 75 | def visit_BLOB(self, type_, **kwargs: Any) -> str: 76 | raise exceptions.NotSupportedError("Type BLOB is not supported") 77 | 78 | def visit_CLOB(self, type_, **kwargs: Any) -> str: 79 | raise exceptions.NotSupportedError("Type CBLOB is not supported") 80 | 81 | def visit_NCLOB(self, type_, **kwargs: Any) -> str: 82 | raise exceptions.NotSupportedError("Type NCBLOB is not supported") 83 | 84 | 85 | class BaseESDialect(default.DefaultDialect): 86 | 87 | name = "SET" 88 | scheme = "SET" 89 | driver = "SET" 90 | statement_compiler: Type[BaseESCompiler] = BaseESCompiler 91 | type_compiler: Type[BaseESTypeCompiler] = BaseESTypeCompiler 92 | preparer = compiler.IdentifierPreparer 93 | supports_alter = False 94 | supports_pk_autoincrement = False 95 | supports_default_values = False 96 | supports_empty_insert = False 97 | supports_unicode_statements = True 98 | supports_unicode_binds = True 99 | returns_unicode_strings = True 100 | description_encoding = None 101 | supports_native_boolean = True 102 | supports_simple_order_by_label = True 103 | 104 | _not_supported_column_types = ["object", "nested"] 105 | 106 | _map_parse_connection_parameters = { 107 | "verify_certs": parse_bool_argument, 108 | "use_ssl": parse_bool_argument, 109 | "http_compress": parse_bool_argument, 110 | "sniff_on_start": parse_bool_argument, 111 | "sniff_on_connection_fail": parse_bool_argument, 112 | "retry_on_timeout": parse_bool_argument, 113 | "sniffer_timeout": int, 114 | "sniff_timeout": int, 115 | "max_retries": int, 116 | "maxsize": int, 117 | "timeout": int, 118 | } 119 | 120 | @classmethod 121 | def dbapi(cls): 122 | return es 123 | 124 | def create_connect_args(self, url): 125 | kwargs = { 126 | "host": url.host, 127 | "port": url.port or 9200, 128 | "path": url.database, 129 | "scheme": self.scheme, 130 | "user": url.username or None, 131 | "password": url.password or None, 132 | } 133 | if url.query: 134 | kwargs.update(url.query) 135 | 136 | for name, parse_func in self._map_parse_connection_parameters.items(): 137 | if name in kwargs: 138 | kwargs[name] = parse_func(url.query[name]) 139 | 140 | return ([], kwargs) 141 | 142 | def get_schema_names(self, connection, **kwargs): 143 | # ES does not have the concept of a schema 144 | return [DEFAULT_SCHEMA] 145 | 146 | def has_table(self, connection, table_name, schema=None): 147 | return table_name in self.get_table_names(connection, schema) 148 | 149 | def get_table_names(self, connection, schema=None, **kwargs) -> List[str]: 150 | pass # pragma: no cover 151 | 152 | def get_columns(self, connection, table_name, schema=None, **kw): 153 | pass # pragma: no cover 154 | 155 | def get_view_names(self, connection, schema=None, **kwargs): 156 | return [] # pragma: no cover 157 | 158 | def get_table_options(self, connection, table_name, schema=None, **kwargs): 159 | return {} 160 | 161 | def get_pk_constraint(self, connection, table_name, schema=None, **kwargs): 162 | return {"constrained_columns": [], "name": None} 163 | 164 | def get_foreign_keys(self, connection, table_name, schema=None, **kwargs): 165 | return [] 166 | 167 | def get_check_constraints(self, connection, table_name, schema=None, **kwargs): 168 | return [] 169 | 170 | def get_table_comment(self, connection, table_name, schema=None, **kwargs): 171 | return {"text": ""} 172 | 173 | def get_indexes(self, connection, table_name, schema=None, **kwargs): 174 | return [] 175 | 176 | def get_unique_constraints(self, connection, table_name, schema=None, **kwargs): 177 | return [] 178 | 179 | def get_view_definition(self, connection, view_name, schema=None, **kwargs): 180 | pass # pragma: no cover 181 | 182 | def do_rollback(self, dbapi_connection): 183 | pass 184 | 185 | def _check_unicode_returns(self, connection, additional_tests=None): 186 | return True 187 | 188 | def _check_unicode_description(self, connection): 189 | return True 190 | 191 | 192 | def get_type(data_type: str) -> int: 193 | type_map = { 194 | "bytes": types.LargeBinary, 195 | "boolean": types.Boolean, 196 | "date": types.DateTime, 197 | "datetime": types.DateTime, 198 | "double": types.Numeric, 199 | "text": types.String, 200 | "keyword": types.String, 201 | "integer": types.Integer, 202 | "half_float": types.Float, 203 | "geo_point": types.String, 204 | # TODO get a solution for nested type 205 | "nested": types.String, 206 | # TODO get a solution for object 207 | "object": types.BLOB, 208 | "long": types.BigInteger, 209 | "float": types.Float, 210 | "ip": types.String, 211 | } 212 | type_ = type_map.get(data_type) 213 | if not type_: 214 | logger.warning(f"Unknown type found {data_type} reverting to string") 215 | type_ = types.String 216 | return type_ 217 | -------------------------------------------------------------------------------- /es/const.py: -------------------------------------------------------------------------------- 1 | DEFAULT_SCHEMA = "default" 2 | DEFAULT_SQL_PATH = "_sql" 3 | DEFAULT_FETCH_SIZE = 10000 4 | -------------------------------------------------------------------------------- /es/elastic/__init__.py: -------------------------------------------------------------------------------- 1 | from es.elastic.api import connect 2 | from es.exceptions import ( 3 | DatabaseError, 4 | DataError, 5 | Error, 6 | IntegrityError, 7 | InterfaceError, 8 | InternalError, 9 | NotSupportedError, 10 | OperationalError, 11 | ProgrammingError, 12 | Warning, 13 | ) 14 | 15 | 16 | __all__ = [ 17 | "connect", 18 | "apilevel", 19 | "threadsafety", 20 | "paramstyle", 21 | "DataError", 22 | "DatabaseError", 23 | "Error", 24 | "IntegrityError", 25 | "InterfaceError", 26 | "InternalError", 27 | "NotSupportedError", 28 | "OperationalError", 29 | "ProgrammingError", 30 | "Warning", 31 | ] 32 | 33 | 34 | apilevel = "2.0" 35 | # Threads may share the module and connections 36 | threadsafety = 2 37 | paramstyle = "pyformat" 38 | -------------------------------------------------------------------------------- /es/elastic/api.py: -------------------------------------------------------------------------------- 1 | import re 2 | from typing import Any, Dict, List, Optional, Tuple 3 | 4 | from elasticsearch import Elasticsearch, exceptions as es_exceptions 5 | from es import exceptions 6 | from es.baseapi import ( 7 | apply_parameters, 8 | BaseConnection, 9 | BaseCursor, 10 | check_closed, 11 | CursorDescriptionRow, 12 | get_description_from_columns, 13 | Type, 14 | ) 15 | from packaging import version 16 | 17 | 18 | def connect( 19 | host: str = "localhost", 20 | port: int = 9200, 21 | path: str = "", 22 | scheme: str = "http", 23 | user: Optional[str] = None, 24 | password: Optional[str] = None, 25 | context: Optional[Dict[str, Any]] = None, 26 | **kwargs: Any, 27 | ) -> BaseConnection: 28 | """ 29 | Constructor for creating a connection to the database. 30 | 31 | >>> conn = connect('localhost', 9200) 32 | >>> curs = conn.cursor() 33 | 34 | """ 35 | context = context or {} 36 | return Connection(host, port, path, scheme, user, password, context, **kwargs) 37 | 38 | 39 | class Connection(BaseConnection): 40 | 41 | """Connection to an ES Cluster""" 42 | 43 | def __init__( 44 | self, 45 | host: str = "localhost", 46 | port: int = 9200, 47 | path: str = "", 48 | scheme: str = "http", 49 | user: Optional[str] = None, 50 | password: Optional[str] = None, 51 | context: Optional[Dict[Any, Any]] = None, 52 | **kwargs: Any, 53 | ) -> None: 54 | super().__init__( 55 | host=host, 56 | port=port, 57 | path=path, 58 | scheme=scheme, 59 | user=user, 60 | password=password, 61 | context=context, 62 | **kwargs, 63 | ) 64 | if user and password: 65 | self.es = Elasticsearch(self.url, http_auth=(user, password), **self.kwargs) 66 | else: 67 | self.es = Elasticsearch(self.url, **self.kwargs) 68 | 69 | @check_closed 70 | def cursor(self) -> BaseCursor: 71 | """Return a new Cursor Object using the connection.""" 72 | if self.es: 73 | cursor = Cursor(self.url, self.es, **self.kwargs) 74 | self.cursors.append(cursor) 75 | return cursor 76 | raise exceptions.UnexpectedESInitError() 77 | 78 | 79 | class Cursor(BaseCursor): 80 | 81 | """Connection cursor.""" 82 | 83 | custom_sql_to_method = { 84 | "show valid_tables": "get_valid_table_names", 85 | "show valid_views": "get_valid_view_names", 86 | } 87 | 88 | def __init__(self, url: str, es: Elasticsearch, **kwargs: Any) -> None: 89 | super().__init__(url, es, **kwargs) 90 | self.sql_path = kwargs.get("sql_path") or "_sql" 91 | 92 | def _get_value_for_col_name(self, row: Tuple[Any], name: str) -> Any: 93 | """ 94 | Get the value of a specific column name from a row 95 | :param row: The result row 96 | :param name: The column name 97 | :return: Value 98 | """ 99 | for idx, col_description in enumerate(self.description): 100 | if col_description.name == name: 101 | return row[idx] 102 | 103 | def get_valid_table_view_names(self, type_filter: str) -> "Cursor": 104 | """ 105 | Custom for "SHOW VALID_TABLES" excludes empty indices from the response 106 | Mixes `SHOW TABLES` with direct index access info to exclude indexes 107 | that have no rows so no columns (unless templated). SQLAlchemy will 108 | not support reflection of tables with no columns 109 | 110 | https://github.com/preset-io/elasticsearch-dbapi/issues/38 111 | 112 | :param: type_filter will filter SHOW_TABLES result by BASE_TABLE or VIEW 113 | """ 114 | results = self.execute("SHOW TABLES") 115 | response = self.es.cat.indices(format="json") 116 | 117 | _results = [] 118 | for result in results: 119 | is_empty = False 120 | for item in response: 121 | # First column is TABLE_NAME 122 | if item["index"] == self._get_value_for_col_name(result, "name"): 123 | if int(item["docs.count"]) == 0: 124 | is_empty = True 125 | break 126 | if ( 127 | not is_empty 128 | and self._get_value_for_col_name(result, "type") == type_filter 129 | ): 130 | _results.append(result) 131 | self._results = _results 132 | return self 133 | 134 | def get_valid_table_names(self) -> "Cursor": 135 | # Get the ES cluster version. Since 7.10 the table column name changed #52 136 | cluster_info = self.es.info() 137 | cluster_version = version.parse(cluster_info["version"]["number"]) 138 | if cluster_version >= version.parse("7.10.0"): 139 | return self.get_valid_table_view_names("TABLE") 140 | return self.get_valid_table_view_names("BASE TABLE") 141 | 142 | def get_valid_view_names(self) -> "Cursor": 143 | return self.get_valid_table_view_names("VIEW") 144 | 145 | @check_closed 146 | def execute( 147 | self, operation: str, parameters: Optional[Dict[str, Any]] = None 148 | ) -> "BaseCursor": 149 | cursor = self.custom_sql_to_method_dispatcher(operation) 150 | if cursor: 151 | return cursor 152 | 153 | re_table_name = re.match("SHOW ARRAY_COLUMNS FROM (.*)", operation) 154 | if re_table_name: 155 | return self.get_array_type_columns(re_table_name[1]) 156 | 157 | query = apply_parameters(operation, parameters) 158 | results = self.elastic_query(query) 159 | # We need a list of tuples 160 | rows = [tuple(row) for row in results.get("rows", [])] 161 | columns = results.get("columns") 162 | if not columns: 163 | raise exceptions.DataError( 164 | "Missing columns field, maybe it's an opendistro sql ep" 165 | ) 166 | self._results = rows 167 | self.description = get_description_from_columns(columns) 168 | return self 169 | 170 | def get_array_type_columns(self, table_name: str) -> "Cursor": 171 | """ 172 | Queries the index (table) for just one record 173 | and return a list of array type columns. 174 | This is useful since arrays are not supported by ES SQL 175 | """ 176 | array_columns: List[Tuple[Any, ...]] = [] 177 | try: 178 | response = self.es.search(index=table_name, size=1) 179 | except es_exceptions.ConnectionError as e: 180 | raise exceptions.OperationalError( 181 | f"Error connecting to {self.url}: {e.info}" 182 | ) 183 | except es_exceptions.NotFoundError as e: 184 | raise exceptions.ProgrammingError(f"Error ({e.error}): {e.info}") 185 | try: 186 | if response["hits"]["total"]["value"] == 0: 187 | source = {} 188 | else: 189 | source = response["hits"]["hits"][0]["_source"] 190 | except KeyError as e: 191 | raise exceptions.DataError( 192 | f"Error inferring array type columns {self.url}: {e}" 193 | ) 194 | for col_name, value in source.items(): 195 | # If it's a list (ES Array add to cursor) 196 | if isinstance(value, list): 197 | if len(value) > 0: 198 | # If it's an array of objects add all keys 199 | if isinstance(value[0], dict): 200 | for in_col_name in value[0]: 201 | array_columns.append((f"{col_name}.{in_col_name}",)) 202 | array_columns.append((f"{col_name}.{in_col_name}.keyword",)) 203 | continue 204 | array_columns.append((col_name,)) 205 | array_columns.append((f"{col_name}.keyword",)) 206 | if not array_columns: 207 | array_columns = [] 208 | self.description = [ 209 | CursorDescriptionRow("name", Type.STRING, None, None, None, None, None) 210 | ] 211 | self._results = array_columns 212 | return self 213 | -------------------------------------------------------------------------------- /es/elastic/sqlalchemy.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from types import ModuleType 3 | from typing import Any, Dict, List, Optional 4 | 5 | from es import basesqlalchemy 6 | import es.elastic 7 | from sqlalchemy.engine import Connection 8 | 9 | logger = logging.getLogger(__name__) 10 | 11 | 12 | class ESCompiler(basesqlalchemy.BaseESCompiler): 13 | pass 14 | 15 | 16 | class ESTypeCompiler(basesqlalchemy.BaseESTypeCompiler): 17 | pass 18 | 19 | 20 | class ESDialect(basesqlalchemy.BaseESDialect): 21 | 22 | name = "elasticsearch" 23 | scheme = "http" 24 | driver = "rest" 25 | statement_compiler = ESCompiler 26 | type_compiler = ESTypeCompiler 27 | 28 | @classmethod 29 | def dbapi(cls) -> ModuleType: 30 | return es.elastic 31 | 32 | def get_table_names( 33 | self, connection: Connection, schema: Optional[str] = None, **kwargs: Any 34 | ) -> List[str]: 35 | query = "SHOW VALID_TABLES" 36 | result = connection.execute(query) 37 | # return a list of table names exclude hidden and empty indexes 38 | return [table.name for table in result if table.name[0] != "."] 39 | 40 | def get_view_names( 41 | self, connection: Connection, schema: Optional[str] = None, **kwargs: Any 42 | ) -> List[str]: 43 | query = "SHOW VALID_VIEWS" 44 | result = connection.execute(query) 45 | # return a list of view names (ES aliases) exclude hidden and empty indexes 46 | return [table.name for table in result if table.name[0] != "."] 47 | 48 | def get_columns( 49 | self, 50 | connection: Connection, 51 | table_name: str, 52 | schema: Optional[str] = None, 53 | **kwargs: Any, 54 | ) -> List[Dict[str, Any]]: 55 | query = f'SHOW COLUMNS FROM "{table_name}"' 56 | # Custom SQL 57 | array_columns_ = connection.execute( 58 | f"SHOW ARRAY_COLUMNS FROM {table_name}" 59 | ).fetchall() 60 | # convert cursor rows: List[Tuple[str]] to List[str] 61 | if not array_columns_: 62 | array_columns = [] 63 | else: 64 | array_columns = [col_name.name for col_name in array_columns_] 65 | 66 | all_columns = connection.execute(query) 67 | return [ 68 | { 69 | "name": row.column, 70 | "type": basesqlalchemy.get_type(row.mapping), 71 | "nullable": True, 72 | "default": None, 73 | } 74 | for row in all_columns 75 | if row.mapping not in self._not_supported_column_types 76 | and row.column not in array_columns 77 | ] 78 | 79 | 80 | ESHTTPDialect = ESDialect 81 | 82 | 83 | class ESHTTPSDialect(ESDialect): 84 | 85 | scheme = "https" 86 | default_paramstyle = "pyformat" 87 | -------------------------------------------------------------------------------- /es/exceptions.py: -------------------------------------------------------------------------------- 1 | class Error(Exception): 2 | """Base exception""" 3 | 4 | 5 | class Warning(Exception): 6 | pass 7 | 8 | 9 | class InterfaceError(Error): 10 | pass 11 | 12 | 13 | class DatabaseError(Error): 14 | pass 15 | 16 | 17 | class InternalError(DatabaseError): 18 | pass 19 | 20 | 21 | class OperationalError(DatabaseError): 22 | pass 23 | 24 | 25 | class ProgrammingError(DatabaseError): 26 | pass 27 | 28 | 29 | class IntegrityError(DatabaseError): 30 | pass 31 | 32 | 33 | class DataError(DatabaseError): 34 | pass 35 | 36 | 37 | class NotSupportedError(DatabaseError): 38 | pass 39 | 40 | 41 | class UnexpectedESInitError(Error): 42 | """Should never happen, when a cursor is requested 43 | without an ElasticSearch object being initialized""" 44 | 45 | 46 | class UnexpectedRequestResponse(Error): 47 | """When perform request returns False, only when HTTP method HEAD 48 | and status code 404""" 49 | -------------------------------------------------------------------------------- /es/opendistro/__init__.py: -------------------------------------------------------------------------------- 1 | from es.exceptions import ( 2 | DatabaseError, 3 | DataError, 4 | Error, 5 | IntegrityError, 6 | InterfaceError, 7 | InternalError, 8 | NotSupportedError, 9 | OperationalError, 10 | ProgrammingError, 11 | Warning, 12 | ) 13 | from es.opendistro.api import connect 14 | 15 | 16 | __all__ = [ 17 | "connect", 18 | "apilevel", 19 | "threadsafety", 20 | "paramstyle", 21 | "DataError", 22 | "DatabaseError", 23 | "Error", 24 | "IntegrityError", 25 | "InterfaceError", 26 | "InternalError", 27 | "NotSupportedError", 28 | "OperationalError", 29 | "ProgrammingError", 30 | "Warning", 31 | ] 32 | 33 | 34 | apilevel = "2.0" 35 | # Threads may share the module and connections 36 | threadsafety = 2 37 | paramstyle = "pyformat" 38 | -------------------------------------------------------------------------------- /es/opendistro/api.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from __future__ import division 3 | from __future__ import print_function 4 | from __future__ import unicode_literals 5 | 6 | import re 7 | from typing import Any, Dict, List, Optional, Tuple 8 | 9 | from elasticsearch import Elasticsearch, RequestsHttpConnection 10 | from elasticsearch.exceptions import ConnectionError 11 | from es import exceptions 12 | from es.baseapi import ( 13 | apply_parameters, 14 | BaseConnection, 15 | BaseCursor, 16 | check_closed, 17 | get_description_from_columns, 18 | ) 19 | from es.const import DEFAULT_SCHEMA 20 | 21 | 22 | def connect( 23 | host: str = "localhost", 24 | port: int = 443, 25 | path: str = "", 26 | scheme: str = "https", 27 | user: Optional[str] = None, 28 | password: Optional[str] = None, 29 | context: Optional[Dict[Any, Any]] = None, 30 | **kwargs: Any, 31 | ) -> BaseConnection: 32 | """ 33 | Constructor for creating a connection to the database. 34 | 35 | >>> conn = connect('localhost', 9200) 36 | >>> curs = conn.cursor() 37 | 38 | """ 39 | context = context or {} 40 | return Connection(host, port, path, scheme, user, password, context, **kwargs) 41 | 42 | 43 | class Connection(BaseConnection): 44 | 45 | """Connection to an ES Cluster""" 46 | 47 | def __init__( 48 | self, 49 | host: str = "localhost", 50 | port: int = 443, 51 | path: str = "", 52 | scheme: str = "https", 53 | user: Optional[str] = None, 54 | password: Optional[str] = None, 55 | context: Optional[Dict[Any, Any]] = None, 56 | **kwargs: Any, 57 | ): 58 | super().__init__( 59 | host=host, 60 | port=port, 61 | path=path, 62 | scheme=scheme, 63 | user=user, 64 | password=password, 65 | context=context, 66 | **kwargs, 67 | ) 68 | if user and password and "aws_keys" not in kwargs: 69 | self.es = Elasticsearch(self.url, http_auth=(user, password), **self.kwargs) 70 | # AWS configured credentials on the connection string 71 | elif user and password and "aws_keys" in kwargs and "aws_region" in kwargs: 72 | aws_auth = self._aws_auth(user, password, kwargs["aws_region"]) 73 | kwargs.pop("aws_keys") 74 | kwargs.pop("aws_region") 75 | 76 | self.es = Elasticsearch( 77 | self.url, 78 | http_auth=aws_auth, 79 | connection_class=RequestsHttpConnection, 80 | **kwargs, 81 | ) 82 | # aws_profile= 83 | elif "aws_profile" in kwargs: 84 | aws_auth = self._aws_auth_profile(kwargs["aws_profile"]) 85 | self.es = Elasticsearch( 86 | self.url, 87 | http_auth=aws_auth, 88 | connection_class=RequestsHttpConnection, 89 | **kwargs, 90 | ) 91 | else: 92 | self.es = Elasticsearch(self.url, **self.kwargs) 93 | 94 | @staticmethod 95 | def _aws_auth_profile(region: str) -> Any: 96 | from requests_aws4auth import AWS4Auth 97 | import boto3 98 | 99 | service = "es" 100 | credentials = boto3.Session().get_credentials() 101 | return AWS4Auth( 102 | credentials.access_key, 103 | credentials.secret_key, 104 | region, 105 | service, 106 | session_token=credentials.token, 107 | ) 108 | 109 | @staticmethod 110 | def _aws_auth(aws_access_key: str, aws_secret_key: str, region: str) -> Any: 111 | from requests_aws4auth import AWS4Auth 112 | 113 | return AWS4Auth(aws_access_key, aws_secret_key, region, "es") 114 | 115 | @check_closed 116 | def cursor(self) -> "Cursor": 117 | """Return a new Cursor Object using the connection.""" 118 | if self.es: 119 | cursor = Cursor(self.url, self.es, **self.kwargs) 120 | self.cursors.append(cursor) 121 | return cursor 122 | raise exceptions.UnexpectedESInitError() 123 | 124 | 125 | class Cursor(BaseCursor): 126 | 127 | custom_sql_to_method = { 128 | "show valid_tables": "get_valid_table_names", 129 | "show valid_views": "get_valid_view_names", 130 | "select 1": "get_valid_select_one", 131 | } 132 | 133 | def __init__(self, url: str, es: Elasticsearch, **kwargs: Any) -> None: 134 | super().__init__(url, es, **kwargs) 135 | self.sql_path = kwargs.get("sql_path") or "_opendistro/_sql" 136 | # Opendistro SQL v2 flag 137 | self.v2 = kwargs.get("v2", False) 138 | if self.v2: 139 | self.fetch_size = None 140 | 141 | def get_valid_table_names(self) -> "Cursor": 142 | """ 143 | Custom for "SHOW VALID_TABLES" excludes empty indices from the response 144 | Mixes `SHOW TABLES LIKE` with direct index access info to exclude indexes 145 | that have no rows so no columns (unless templated). SQLAlchemy will 146 | not support reflection of tables with no columns 147 | 148 | https://github.com/preset-io/elasticsearch-dbapi/issues/38 149 | """ 150 | results = self.execute("SHOW TABLES LIKE %") 151 | response = self.es.cat.indices(format="json") 152 | 153 | _results = [] 154 | for result in results: 155 | is_empty = False 156 | for item in response: 157 | # Third column is TABLE_NAME 158 | if item["index"] == result[2]: 159 | if int(item["docs.count"]) == 0: 160 | is_empty = True 161 | break 162 | if not is_empty: 163 | _results.append(result) 164 | self._results = _results 165 | return self 166 | 167 | def get_valid_view_names(self) -> "Cursor": 168 | """ 169 | Custom for "SHOW VALID_VIEWS" excludes empty indices from the response 170 | https://github.com/preset-io/elasticsearch-dbapi/issues/38 171 | """ 172 | if self.v2: 173 | # On v2 an alias is represented has a table 174 | return self 175 | response = self.es.cat.aliases(format="json") 176 | results: List[Tuple[str, ...]] = [] 177 | for item in response: 178 | results.append((item["alias"], item["index"])) 179 | self.description = get_description_from_columns( 180 | [ 181 | {"name": "VIEW_NAME", "type": "text"}, 182 | {"name": "TABLE_NAME", "type": "text"}, 183 | ] 184 | ) 185 | self._results = results 186 | return self 187 | 188 | def _traverse_mapping( 189 | self, 190 | mapping: Dict[str, Any], 191 | results: List[Tuple[str, ...]], 192 | parent_field_name: Optional[str] = None, 193 | ) -> List[Tuple[str, ...]]: 194 | """ 195 | Traverses an Elasticsearch mapping and returns a flattened list 196 | of fields and types. Nested fields are flattened using dotted notation 197 | 198 | :param mapping: An elastic search mapping 199 | :param results: A list of fields and types 200 | :param parent_field_name: recursively append 201 | child field names to parent field names 202 | :return: A flattened list of fields and types 203 | """ 204 | for field_name, metadata in mapping.items(): 205 | if parent_field_name: 206 | field_name = f"{parent_field_name}.{field_name}" 207 | if "properties" in metadata: 208 | self._traverse_mapping(metadata["properties"], results, field_name) 209 | else: 210 | results.append((field_name, metadata["type"])) 211 | if "fields" in metadata: 212 | for sub_field_name, sub_metadata in metadata["fields"].items(): 213 | # V2 does not recognize keyword fields 214 | if sub_field_name.endswith("keyword") and self.v2: 215 | continue 216 | results.append( 217 | (f"{field_name}.{sub_field_name}", sub_metadata["type"]) 218 | ) 219 | return results 220 | 221 | def get_valid_columns(self, index_name: str) -> "Cursor": 222 | """ 223 | Custom for "SHOW VALID_COLUMNS FROM " 224 | Adds keywords to text if they exist and flattens nested structures 225 | get's all fields by directly accessing `/_mapping/` endpoint 226 | 227 | https://github.com/preset-io/elasticsearch-dbapi/issues/38 228 | """ 229 | response = self.es.indices.get_mapping(index=index_name, format="json") 230 | # When the index is an alias the first key is the real index name 231 | try: 232 | index_real_name = list(response.keys())[0] 233 | except IndexError: 234 | raise exceptions.DataError("Index mapping returned and unexpected response") 235 | self._results = self._traverse_mapping( 236 | response[index_real_name]["mappings"]["properties"], [] 237 | ) 238 | 239 | self.description = get_description_from_columns( 240 | [ 241 | {"name": "COLUMN_NAME", "type": "text"}, 242 | {"name": "TYPE_NAME", "type": "text"}, 243 | ] 244 | ) 245 | return self 246 | 247 | def get_valid_select_one(self) -> "Cursor": 248 | """ 249 | Currently Opendistro SQL endpoint does not support SELECT 1 250 | So we use Elasticsearch ping method 251 | 252 | :return: A cursor with "1" (result from SELECT 1) 253 | :raises: DatabaseError in case of a connection error 254 | """ 255 | try: 256 | res = self.es.ping() 257 | except ConnectionError: 258 | raise exceptions.DatabaseError("Connection failed") 259 | if not res: 260 | raise exceptions.DatabaseError("Connection failed") 261 | self._results = [(1,)] 262 | self.description = get_description_from_columns([{"name": "1", "type": "long"}]) 263 | return self 264 | 265 | @check_closed 266 | def execute( 267 | self, operation: str, parameters: Optional[Dict[str, Any]] = None 268 | ) -> "BaseCursor": 269 | cursor = self.custom_sql_to_method_dispatcher(operation) 270 | if cursor: 271 | return cursor 272 | 273 | re_table_name = re.match("SHOW VALID_COLUMNS FROM (.*)", operation) 274 | if re_table_name: 275 | return self.get_valid_columns(re_table_name[1]) 276 | 277 | query = apply_parameters(operation, parameters) 278 | results = self.elastic_query(query) 279 | 280 | rows = [tuple(row) for row in results.get("datarows", [])] 281 | columns = results.get("schema") 282 | if not columns: 283 | raise exceptions.DataError( 284 | "Missing columns field, maybe it's an elastic sql ep" 285 | ) 286 | self._results = rows 287 | self.description = get_description_from_columns(columns) 288 | return self 289 | 290 | def sanitize_query(self, query: str) -> str: 291 | query = query.replace('"', "") 292 | query = query.replace(" ", " ") 293 | query = query.replace("\n", " ") 294 | # remove dummy schema from queries 295 | return query.replace(f"FROM {DEFAULT_SCHEMA}.", "FROM ") 296 | -------------------------------------------------------------------------------- /es/opendistro/sqlalchemy.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from types import ModuleType 3 | from typing import Any, Dict, List, Optional 4 | 5 | from es import basesqlalchemy 6 | import es.opendistro 7 | from sqlalchemy.engine import Connection 8 | from sqlalchemy.sql import compiler 9 | 10 | logger = logging.getLogger(__name__) 11 | 12 | 13 | class ESCompiler(basesqlalchemy.BaseESCompiler): # pragma: no cover 14 | pass 15 | 16 | 17 | class ESTypeCompiler(basesqlalchemy.BaseESTypeCompiler): # pragma: no cover 18 | pass 19 | 20 | 21 | class ESTypeIdentifierPreparer(compiler.IdentifierPreparer): 22 | def __init__(self, *args: Any, **kwargs: Any): 23 | super().__init__(*args, **kwargs) 24 | 25 | self.initial_quote = self.final_quote = "`" 26 | 27 | 28 | class ESDialect(basesqlalchemy.BaseESDialect): 29 | 30 | name = "odelasticsearch" 31 | scheme = "http" 32 | driver = "rest" 33 | statement_compiler = ESCompiler 34 | type_compiler = ESTypeCompiler 35 | preparer = ESTypeIdentifierPreparer 36 | 37 | @classmethod 38 | def dbapi(cls) -> ModuleType: 39 | return es.opendistro 40 | 41 | def get_table_names( 42 | self, connection: Connection, schema: Optional[str] = None, **kwargs: Any 43 | ) -> List[str]: 44 | # custom builtin query 45 | query = "SHOW VALID_TABLES" 46 | result = connection.execute(query) 47 | # return a list of table names exclude hidden and empty indexes 48 | return [table.TABLE_NAME for table in result if table.TABLE_NAME[0] != "."] 49 | 50 | def get_view_names( 51 | self, connection: Connection, schema: Optional[str] = None, **kwargs: Any 52 | ) -> List[str]: 53 | # custom builtin query 54 | query = "SHOW VALID_VIEWS" 55 | result = connection.execute(query) 56 | # return a list of table names exclude hidden and empty indexes 57 | return [table.VIEW_NAME for table in result if table.VIEW_NAME[0] != "."] 58 | 59 | def get_columns( 60 | self, 61 | connection: Connection, 62 | table_name: str, 63 | schema: Optional[str] = None, 64 | **kwargs: Any, 65 | ) -> List[Dict[str, Any]]: 66 | # custom builtin query 67 | query = f"SHOW VALID_COLUMNS FROM {table_name}" 68 | 69 | result = connection.execute(query) 70 | return [ 71 | { 72 | "name": row.COLUMN_NAME, 73 | "type": basesqlalchemy.get_type(row.TYPE_NAME), 74 | "nullable": True, 75 | "default": None, 76 | } 77 | for row in result 78 | if row.TYPE_NAME not in self._not_supported_column_types 79 | ] 80 | 81 | 82 | ESHTTPDialect = ESDialect 83 | 84 | 85 | class ESHTTPSDialect(ESDialect): 86 | 87 | scheme = "https" 88 | default_paramstyle = "pyformat" 89 | _not_supported_column_types = ["nested", "geo_point", "alias"] 90 | -------------------------------------------------------------------------------- /es/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/preset-io/elasticsearch-dbapi/ce3df30449626fdf44cbe4bebe07bb65b449b8c0/es/tests/__init__.py -------------------------------------------------------------------------------- /es/tests/fixtures/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/preset-io/elasticsearch-dbapi/ce3df30449626fdf44cbe4bebe07bb65b449b8c0/es/tests/fixtures/__init__.py -------------------------------------------------------------------------------- /es/tests/fixtures/data1.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "field_str" : "str1", 4 | "field_boolean": true, 5 | "field_number" : 1, 6 | "field_float": 0.1, 7 | "field_array" : [ 8 | "n1", 9 | "n2" 10 | ], 11 | "location": { 12 | "lat": 41.12, 13 | "lon": -71.34 14 | }, 15 | "field_nested": { 16 | "c1": "c1", 17 | "c2": 1 18 | }, 19 | "timestamp" : "2019-10-13T00:00:00.000Z" 20 | }, 21 | { 22 | "field_str" : "str2", 23 | "field_boolean": true, 24 | "field_number" : 2, 25 | "field_float": 0.2, 26 | "field_array" : [ 27 | "n1", 28 | "n2" 29 | ], 30 | "location": { 31 | "lat": 0.12, 32 | "lon": -11.34 33 | }, 34 | "field_nested": { 35 | "c1": "c2", 36 | "c2": 2 37 | }, 38 | "timestamp" : "2019-10-13T00:00:01.000Z" 39 | }, 40 | { 41 | "field_str" : "str3", 42 | "field_boolean": false, 43 | "field_number" : 3, 44 | "field_float": 0.3, 45 | "field_array" : [ 46 | "n1", 47 | "n2" 48 | ], 49 | "location": { 50 | "lat": 41.22, 51 | "lon": -21.14 52 | }, 53 | "field_nested": { 54 | "c1": "c3", 55 | "c2": 3 56 | }, 57 | "timestamp" : "2019-10-13T00:00:02.000Z" 58 | } 59 | ] 60 | -------------------------------------------------------------------------------- /es/tests/fixtures/data1_mappings.json: -------------------------------------------------------------------------------- 1 | { 2 | "mappings": { 3 | "properties": { 4 | "location": { 5 | "type": "geo_point" 6 | } 7 | } 8 | } 9 | } 10 | 11 | -------------------------------------------------------------------------------- /es/tests/fixtures/fixtures.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | from typing import Any, Dict, Optional 4 | 5 | from elasticsearch import Elasticsearch 6 | from elasticsearch.exceptions import NotFoundError 7 | 8 | 9 | flights_columns = [ 10 | "AvgTicketPrice", 11 | "Cancelled", 12 | "Carrier", 13 | "Carrier.keyword", 14 | "Dest", 15 | "Dest.keyword", 16 | "DestAirportID", 17 | "DestAirportID.keyword", 18 | "DestCityName", 19 | "DestCityName.keyword", 20 | "DestCountry", 21 | "DestCountry.keyword", 22 | "DestLocation.lat", 23 | "DestLocation.lat.keyword", 24 | "DestLocation.lon", 25 | "DestLocation.lon.keyword", 26 | "DestRegion", 27 | "DestRegion.keyword", 28 | "DestWeather", 29 | "DestWeather.keyword", 30 | "DistanceKilometers", 31 | "DistanceMiles", 32 | "FlightDelay", 33 | "FlightDelayMin", 34 | "FlightDelayType", 35 | "FlightDelayType.keyword", 36 | "FlightNum", 37 | "FlightNum.keyword", 38 | "FlightTimeHour", 39 | "FlightTimeMin", 40 | "Origin", 41 | "Origin.keyword", 42 | "OriginAirportID", 43 | "OriginAirportID.keyword", 44 | "OriginCityName", 45 | "OriginCityName.keyword", 46 | "OriginCountry", 47 | "OriginCountry.keyword", 48 | "OriginLocation.lat", 49 | "OriginLocation.lat.keyword", 50 | "OriginLocation.lon", 51 | "OriginLocation.lon.keyword", 52 | "OriginRegion", 53 | "OriginRegion.keyword", 54 | "OriginWeather", 55 | "OriginWeather.keyword", 56 | "dayOfWeek", 57 | "timestamp", 58 | ] 59 | 60 | data1_columns = [ 61 | "field_boolean", 62 | "field_float", 63 | "field_nested.c1", 64 | "field_nested.c1.keyword", 65 | "field_nested.c2", 66 | "field_number", 67 | "field_str", 68 | "field_str.keyword", 69 | "location", 70 | "timestamp", 71 | ] 72 | 73 | 74 | def import_file_to_es( 75 | base_url: str, data_path: str, index_name: str, mappings_path: Optional[str] = None 76 | ) -> None: 77 | 78 | with open(data_path, "r") as fd_data: 79 | data = json.load(fd_data) 80 | 81 | mappings = None 82 | if mappings_path: 83 | with open(mappings_path, "r") as fd_mappings: 84 | mappings = json.load(fd_mappings) 85 | 86 | set_index_settings(base_url, index_name, mappings=mappings) 87 | es = Elasticsearch(base_url, verify_certs=False) 88 | for doc in data: 89 | es.index(index=index_name, doc_type="_doc", body=doc, refresh=True) 90 | 91 | 92 | def set_index_settings( 93 | base_url: str, index_name: str, mappings: Optional[Dict[str, Any]] = None 94 | ) -> None: 95 | """ 96 | Sets index settings for number of replicas to ZERO by default, and applies optional 97 | mappings 98 | """ 99 | body = {"settings": {"number_of_shards": 1, "number_of_replicas": 0}} 100 | if mappings: 101 | body.update(mappings) 102 | es = Elasticsearch(base_url, verify_certs=False) 103 | es.indices.create(index=index_name, ignore=400, body=body) 104 | 105 | 106 | def delete_index(base_url, index_name: str) -> None: 107 | es = Elasticsearch(base_url, verify_certs=False) 108 | try: 109 | es.delete_by_query(index=index_name, body={"query": {"match_all": {}}}) 110 | except NotFoundError: 111 | return 112 | 113 | 114 | def delete_alias(base_url, alias_name: str, index_name: str) -> None: 115 | es = Elasticsearch(base_url, verify_certs=False) 116 | try: 117 | es.indices.delete_alias(index=index_name, name=alias_name) 118 | except NotFoundError: 119 | return 120 | 121 | 122 | def create_alias(base_url, alias_name: str, index_name: str) -> None: 123 | es = Elasticsearch(base_url, verify_certs=False) 124 | try: 125 | es.indices.put_alias(index=index_name, name=alias_name) 126 | except NotFoundError: 127 | return 128 | 129 | 130 | def import_flights(base_url: str) -> None: 131 | path = os.path.join(os.path.dirname(__file__), "flights.json") 132 | import_file_to_es(base_url, path, "flights") 133 | 134 | 135 | def import_data1(base_url: str) -> None: 136 | data_path = os.path.join(os.path.dirname(__file__), "data1.json") 137 | mappings_path = os.path.join(os.path.dirname(__file__), "data1_mappings.json") 138 | 139 | import_file_to_es(base_url, data_path, "data1", mappings_path=mappings_path) 140 | 141 | 142 | def import_empty_index(base_url): 143 | set_index_settings(base_url, "empty_index") 144 | -------------------------------------------------------------------------------- /es/tests/fixtures/flights.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "FlightNum": "9HY9SWR", 4 | "DestCountry": "AU", 5 | "OriginWeather": "Sunny", 6 | "OriginCityName": "Frankfurt am Main", 7 | "AvgTicketPrice": 841.2656419677076, 8 | "DistanceMiles": 10247.856675613455, 9 | "FlightDelay": false, 10 | "DestWeather": "Rain", 11 | "Dest": "Sydney Kingsford Smith International Airport", 12 | "FlightDelayType": "No Delay", 13 | "OriginCountry": "DE", 14 | "dayOfWeek": 0, 15 | "DistanceKilometers": 16492.32665375846, 16 | "timestamp": "2019-09-16T00:00:00", 17 | "DestLocation": { 18 | "lat": "-33.94609833", 19 | "lon": "151.177002" 20 | }, 21 | "DestAirportID": "SYD", 22 | "Carrier": "Kibana Airlines", 23 | "Cancelled": false, 24 | "FlightTimeMin": 1030.7704158599038, 25 | "Origin": "Frankfurt am Main Airport", 26 | "OriginLocation": { 27 | "lat": "50.033333", 28 | "lon": "8.570556" 29 | }, 30 | "DestRegion": "SE-BD", 31 | "OriginAirportID": "FRA", 32 | "OriginRegion": "DE-HE", 33 | "DestCityName": "Sydney", 34 | "FlightTimeHour": 17.179506930998397, 35 | "FlightDelayMin": 0 36 | }, 37 | { 38 | "FlightNum": "X98CCZO", 39 | "DestCountry": "IT", 40 | "OriginWeather": "Clear", 41 | "OriginCityName": "Cape Town", 42 | "AvgTicketPrice": 882.9826615595518, 43 | "DistanceMiles": 5482.606664853586, 44 | "FlightDelay": false, 45 | "DestWeather": "Sunny", 46 | "Dest": "Venice Marco Polo Airport", 47 | "FlightDelayType": "No Delay", 48 | "OriginCountry": "ZA", 49 | "dayOfWeek": 0, 50 | "DistanceKilometers": 8823.40014044213, 51 | "timestamp": "2019-09-16T18:27:00", 52 | "DestLocation": { 53 | "lat": "45.505299", 54 | "lon": "12.3519" 55 | }, 56 | "DestAirportID": "VE05", 57 | "Carrier": "Logstash Airways", 58 | "Cancelled": false, 59 | "FlightTimeMin": 464.3894810759016, 60 | "Origin": "Cape Town International Airport", 61 | "OriginLocation": { 62 | "lat": "-33.96480179", 63 | "lon": "18.60169983" 64 | }, 65 | "DestRegion": "IT-34", 66 | "OriginAirportID": "CPT", 67 | "OriginRegion": "SE-BD", 68 | "DestCityName": "Venice", 69 | "FlightTimeHour": 7.73982468459836, 70 | "FlightDelayMin": 0 71 | }, 72 | { 73 | "FlightNum": "UFK2WIZ", 74 | "DestCountry": "IT", 75 | "OriginWeather": "Rain", 76 | "OriginCityName": "Venice", 77 | "AvgTicketPrice": 190.6369038508356, 78 | "DistanceMiles": 0, 79 | "FlightDelay": false, 80 | "DestWeather": "Cloudy", 81 | "Dest": "Venice Marco Polo Airport", 82 | "FlightDelayType": "No Delay", 83 | "OriginCountry": "IT", 84 | "dayOfWeek": 0, 85 | "DistanceKilometers": 0, 86 | "timestamp": "2019-09-16T17:11:14", 87 | "DestLocation": { 88 | "lat": "45.505299", 89 | "lon": "12.3519" 90 | }, 91 | "DestAirportID": "VE05", 92 | "Carrier": "Logstash Airways", 93 | "Cancelled": false, 94 | "FlightTimeMin": 0, 95 | "Origin": "Venice Marco Polo Airport", 96 | "OriginLocation": { 97 | "lat": "45.505299", 98 | "lon": "12.3519" 99 | }, 100 | "DestRegion": "IT-34", 101 | "OriginAirportID": "VE05", 102 | "OriginRegion": "IT-34", 103 | "DestCityName": "Venice", 104 | "FlightTimeHour": 0, 105 | "FlightDelayMin": 0 106 | }, 107 | { 108 | "FlightNum": "EAYQW69", 109 | "DestCountry": "IT", 110 | "OriginWeather": "Thunder & Lightning", 111 | "OriginCityName": "Naples", 112 | "AvgTicketPrice": 181.69421554118, 113 | "DistanceMiles": 345.31943877289535, 114 | "FlightDelay": true, 115 | "DestWeather": "Clear", 116 | "Dest": "Treviso-Sant'Angelo Airport", 117 | "FlightDelayType": "Weather Delay", 118 | "OriginCountry": "IT", 119 | "dayOfWeek": 0, 120 | "DistanceKilometers": 555.7377668725265, 121 | "timestamp": "2019-09-16T10:33:28", 122 | "DestLocation": { 123 | "lat": "45.648399", 124 | "lon": "12.1944" 125 | }, 126 | "DestAirportID": "TV01", 127 | "Carrier": "Kibana Airlines", 128 | "Cancelled": true, 129 | "FlightTimeMin": 222.74905899019436, 130 | "Origin": "Naples International Airport", 131 | "OriginLocation": { 132 | "lat": "40.886002", 133 | "lon": "14.2908" 134 | }, 135 | "DestRegion": "IT-34", 136 | "OriginAirportID": "NA01", 137 | "OriginRegion": "IT-72", 138 | "DestCityName": "Treviso", 139 | "FlightTimeHour": 3.712484316503239, 140 | "FlightDelayMin": 180 141 | }, 142 | { 143 | "FlightNum": "58U013N", 144 | "DestCountry": "CN", 145 | "OriginWeather": "Damaging Wind", 146 | "OriginCityName": "Mexico City", 147 | "AvgTicketPrice": 730.041778346198, 148 | "DistanceMiles": 8300.428124665925, 149 | "FlightDelay": false, 150 | "DestWeather": "Clear", 151 | "Dest": "Xi'an Xianyang International Airport", 152 | "FlightDelayType": "No Delay", 153 | "OriginCountry": "MX", 154 | "dayOfWeek": 0, 155 | "DistanceKilometers": 13358.24419986236, 156 | "timestamp": "2019-09-16T05:13:00", 157 | "DestLocation": { 158 | "lat": "34.447102", 159 | "lon": "108.751999" 160 | }, 161 | "DestAirportID": "XIY", 162 | "Carrier": "Kibana Airlines", 163 | "Cancelled": false, 164 | "FlightTimeMin": 785.7790705801389, 165 | "Origin": "Licenciado Benito Juarez International Airport", 166 | "OriginLocation": { 167 | "lat": "19.4363", 168 | "lon": "-99.072098" 169 | }, 170 | "DestRegion": "SE-BD", 171 | "OriginAirportID": "AICM", 172 | "OriginRegion": "MX-DIF", 173 | "DestCityName": "Xi'an", 174 | "FlightTimeHour": 13.096317843002314, 175 | "FlightDelayMin": 0 176 | }, 177 | { 178 | "FlightNum": "XEJ78I2", 179 | "DestCountry": "IT", 180 | "OriginWeather": "Rain", 181 | "OriginCityName": "Edmonton", 182 | "AvgTicketPrice": 418.1520890531832, 183 | "DistanceMiles": 4891.315227492962, 184 | "FlightDelay": false, 185 | "DestWeather": "Thunder & Lightning", 186 | "Dest": "Genoa Cristoforo Colombo Airport", 187 | "FlightDelayType": "No Delay", 188 | "OriginCountry": "CA", 189 | "dayOfWeek": 0, 190 | "DistanceKilometers": 7871.808813474433, 191 | "timestamp": "2019-09-16T01:43:03", 192 | "DestLocation": { 193 | "lat": "44.4133", 194 | "lon": "8.8375" 195 | }, 196 | "DestAirportID": "GE01", 197 | "Carrier": "JetBeats", 198 | "Cancelled": false, 199 | "FlightTimeMin": 393.5904406737217, 200 | "Origin": "Edmonton International Airport", 201 | "OriginLocation": { 202 | "lat": "53.30970001", 203 | "lon": "-113.5800018" 204 | }, 205 | "DestRegion": "IT-42", 206 | "OriginAirportID": "CYEG", 207 | "OriginRegion": "CA-AB", 208 | "DestCityName": "Genova", 209 | "FlightTimeHour": 6.5598406778953615, 210 | "FlightDelayMin": 0 211 | }, 212 | { 213 | "FlightNum": "EVARI8I", 214 | "DestCountry": "CH", 215 | "OriginWeather": "Clear", 216 | "OriginCityName": "Zurich", 217 | "AvgTicketPrice": 180.24681638061213, 218 | "DistanceMiles": 0, 219 | "FlightDelay": true, 220 | "DestWeather": "Hail", 221 | "Dest": "Zurich Airport", 222 | "FlightDelayType": "Security Delay", 223 | "OriginCountry": "CH", 224 | "dayOfWeek": 0, 225 | "DistanceKilometers": 0, 226 | "timestamp": "2019-09-16T13:49:53", 227 | "DestLocation": { 228 | "lat": "47.464699", 229 | "lon": "8.54917" 230 | }, 231 | "DestAirportID": "ZRH", 232 | "Carrier": "JetBeats", 233 | "Cancelled": false, 234 | "FlightTimeMin": 300, 235 | "Origin": "Zurich Airport", 236 | "OriginLocation": { 237 | "lat": "47.464699", 238 | "lon": "8.54917" 239 | }, 240 | "DestRegion": "CH-ZH", 241 | "OriginAirportID": "ZRH", 242 | "OriginRegion": "CH-ZH", 243 | "DestCityName": "Zurich", 244 | "FlightTimeHour": 5, 245 | "FlightDelayMin": 300 246 | }, 247 | { 248 | "FlightNum": "1IRBW25", 249 | "DestCountry": "CA", 250 | "OriginWeather": "Thunder & Lightning", 251 | "OriginCityName": "Rome", 252 | "AvgTicketPrice": 585.1843103083941, 253 | "DistanceMiles": 4203.1829639346715, 254 | "FlightDelay": false, 255 | "DestWeather": "Clear", 256 | "Dest": "Ottawa Macdonald-Cartier International Airport", 257 | "FlightDelayType": "No Delay", 258 | "OriginCountry": "IT", 259 | "dayOfWeek": 0, 260 | "DistanceKilometers": 6764.367283910481, 261 | "timestamp": "2019-09-16T04:54:59", 262 | "DestLocation": { 263 | "lat": "45.32249832", 264 | "lon": "-75.66919708" 265 | }, 266 | "DestAirportID": "YOW", 267 | "Carrier": "Kibana Airlines", 268 | "Cancelled": false, 269 | "FlightTimeMin": 614.9424803554983, 270 | "Origin": "Ciampino___G. B. Pastine International Airport", 271 | "OriginLocation": { 272 | "lat": "41.7994", 273 | "lon": "12.5949" 274 | }, 275 | "DestRegion": "CA-ON", 276 | "OriginAirportID": "RM12", 277 | "OriginRegion": "IT-62", 278 | "DestCityName": "Ottawa", 279 | "FlightTimeHour": 10.249041339258305, 280 | "FlightDelayMin": 0 281 | }, 282 | { 283 | "FlightNum": "M05KE88", 284 | "DestCountry": "IN", 285 | "OriginWeather": "Heavy Fog", 286 | "OriginCityName": "Milan", 287 | "AvgTicketPrice": 960.8697358054351, 288 | "DistanceMiles": 4377.166776556647, 289 | "FlightDelay": true, 290 | "DestWeather": "Cloudy", 291 | "Dest": "Rajiv Gandhi International Airport", 292 | "FlightDelayType": "NAS Delay", 293 | "OriginCountry": "IT", 294 | "dayOfWeek": 0, 295 | "DistanceKilometers": 7044.367088850781, 296 | "timestamp": "2019-09-16T12:09:35", 297 | "DestLocation": { 298 | "lat": "17.23131752", 299 | "lon": "78.42985535" 300 | }, 301 | "DestAirportID": "HYD", 302 | "Carrier": "Kibana Airlines", 303 | "Cancelled": true, 304 | "FlightTimeMin": 602.0305907375651, 305 | "Origin": "Milano Linate Airport", 306 | "OriginLocation": { 307 | "lat": "45.445099", 308 | "lon": "9.27674" 309 | }, 310 | "DestRegion": "SE-BD", 311 | "OriginAirportID": "MI11", 312 | "OriginRegion": "IT-25", 313 | "DestCityName": "Hyderabad", 314 | "FlightTimeHour": 10.033843178959419, 315 | "FlightDelayMin": 15 316 | }, 317 | { 318 | "FlightNum": "SNI3M1Z", 319 | "DestCountry": "IT", 320 | "OriginWeather": "Cloudy", 321 | "OriginCityName": "Moscow", 322 | "AvgTicketPrice": 296.8777725965789, 323 | "DistanceMiles": 1303.5538675692512, 324 | "FlightDelay": false, 325 | "DestWeather": "Rain", 326 | "Dest": "Treviso-Sant'Angelo Airport", 327 | "FlightDelayType": "No Delay", 328 | "OriginCountry": "RU", 329 | "dayOfWeek": 0, 330 | "DistanceKilometers": 2097.866595449369, 331 | "timestamp": "2019-09-16T12:09:35", 332 | "DestLocation": { 333 | "lat": "45.648399", 334 | "lon": "12.1944" 335 | }, 336 | "DestAirportID": "TV01", 337 | "Carrier": "Logstash Airways", 338 | "Cancelled": false, 339 | "FlightTimeMin": 174.82221628744742, 340 | "Origin": "Sheremetyevo International Airport", 341 | "OriginLocation": { 342 | "lat": "55.972599", 343 | "lon": "37.4146" 344 | }, 345 | "DestRegion": "IT-34", 346 | "OriginAirportID": "SVO", 347 | "OriginRegion": "RU-MOS", 348 | "DestCityName": "Treviso", 349 | "FlightTimeHour": 2.9137036047907903, 350 | "FlightDelayMin": 0 351 | }, 352 | { 353 | "FlightNum": "JQ2XXQ5", 354 | "DestCountry": "FI", 355 | "OriginWeather": "Rain", 356 | "OriginCityName": "Albuquerque", 357 | "AvgTicketPrice": 906.4379477399872, 358 | "DistanceMiles": 5313.8222112173335, 359 | "FlightDelay": false, 360 | "DestWeather": "Rain", 361 | "Dest": "Helsinki Vantaa Airport", 362 | "FlightDelayType": "No Delay", 363 | "OriginCountry": "US", 364 | "dayOfWeek": 0, 365 | "DistanceKilometers": 8551.76789268935, 366 | "timestamp": "2019-09-16T22:06:14", 367 | "DestLocation": { 368 | "lat": "60.31719971", 369 | "lon": "24.9633007" 370 | }, 371 | "DestAirportID": "HEL", 372 | "Carrier": "JetBeats", 373 | "Cancelled": false, 374 | "FlightTimeMin": 503.04517015819704, 375 | "Origin": "Albuquerque International Sunport Airport", 376 | "OriginLocation": { 377 | "lat": "35.040199", 378 | "lon": "-106.609001" 379 | }, 380 | "DestRegion": "FI-ES", 381 | "OriginAirportID": "ABQ", 382 | "OriginRegion": "US-NM", 383 | "DestCityName": "Helsinki", 384 | "FlightTimeHour": 8.384086169303284, 385 | "FlightDelayMin": 0 386 | }, 387 | { 388 | "FlightNum": "V30ITD0", 389 | "DestCountry": "AT", 390 | "OriginWeather": "Rain", 391 | "OriginCityName": "Venice", 392 | "AvgTicketPrice": 704.4637710312036, 393 | "DistanceMiles": 268.99172653633303, 394 | "FlightDelay": false, 395 | "DestWeather": "Cloudy", 396 | "Dest": "Vienna International Airport", 397 | "FlightDelayType": "No Delay", 398 | "OriginCountry": "IT", 399 | "dayOfWeek": 0, 400 | "DistanceKilometers": 432.90022115088834, 401 | "timestamp": "2019-09-16T11:52:34", 402 | "DestLocation": { 403 | "lat": "48.11029816", 404 | "lon": "16.56970024" 405 | }, 406 | "DestAirportID": "VIE", 407 | "Carrier": "Logstash Airways", 408 | "Cancelled": false, 409 | "FlightTimeMin": 36.07501842924069, 410 | "Origin": "Venice Marco Polo Airport", 411 | "OriginLocation": { 412 | "lat": "45.505299", 413 | "lon": "12.3519" 414 | }, 415 | "DestRegion": "AT-9", 416 | "OriginAirportID": "VE05", 417 | "OriginRegion": "IT-34", 418 | "DestCityName": "Vienna", 419 | "FlightTimeHour": 0.6012503071540115, 420 | "FlightDelayMin": 0 421 | }, 422 | { 423 | "FlightNum": "P0WMFH7", 424 | "DestCountry": "CN", 425 | "OriginWeather": "Heavy Fog", 426 | "OriginCityName": "Mexico City", 427 | "AvgTicketPrice": 922.499077027416, 428 | "DistanceMiles": 8025.381414737853, 429 | "FlightDelay": false, 430 | "DestWeather": "Clear", 431 | "Dest": "Shanghai Pudong International Airport", 432 | "FlightDelayType": "No Delay", 433 | "OriginCountry": "MX", 434 | "dayOfWeek": 0, 435 | "DistanceKilometers": 12915.599427519877, 436 | "timestamp": "2019-09-16T02:13:46", 437 | "DestLocation": { 438 | "lat": "31.14340019", 439 | "lon": "121.8050003" 440 | }, 441 | "DestAirportID": "PVG", 442 | "Carrier": "Logstash Airways", 443 | "Cancelled": true, 444 | "FlightTimeMin": 679.7683909220988, 445 | "Origin": "Licenciado Benito Juarez International Airport", 446 | "OriginLocation": { 447 | "lat": "19.4363", 448 | "lon": "-99.072098" 449 | }, 450 | "DestRegion": "SE-BD", 451 | "OriginAirportID": "AICM", 452 | "OriginRegion": "MX-DIF", 453 | "DestCityName": "Shanghai", 454 | "FlightTimeHour": 11.32947318203498, 455 | "FlightDelayMin": 0 456 | }, 457 | { 458 | "FlightNum": "VT9O2KD", 459 | "DestCountry": "CA", 460 | "OriginWeather": "Rain", 461 | "OriginCityName": "Naples", 462 | "AvgTicketPrice": 374.9592762864519, 463 | "DistanceMiles": 4311.560440686985, 464 | "FlightDelay": false, 465 | "DestWeather": "Rain", 466 | "Dest": "Ottawa Macdonald-Cartier International Airport", 467 | "FlightDelayType": "No Delay", 468 | "OriginCountry": "IT", 469 | "dayOfWeek": 0, 470 | "DistanceKilometers": 6938.783925856956, 471 | "timestamp": "2019-09-16T14:21:13", 472 | "DestLocation": { 473 | "lat": "45.32249832", 474 | "lon": "-75.66919708" 475 | }, 476 | "DestAirportID": "YOW", 477 | "Carrier": "Logstash Airways", 478 | "Cancelled": false, 479 | "FlightTimeMin": 330.41828218366453, 480 | "Origin": "Naples International Airport", 481 | "OriginLocation": { 482 | "lat": "40.886002", 483 | "lon": "14.2908" 484 | }, 485 | "DestRegion": "CA-ON", 486 | "OriginAirportID": "NA01", 487 | "OriginRegion": "IT-72", 488 | "DestCityName": "Ottawa", 489 | "FlightTimeHour": 5.506971369727742, 490 | "FlightDelayMin": 0 491 | }, 492 | { 493 | "FlightNum": "NRHSVG8", 494 | "DestCountry": "PR", 495 | "OriginWeather": "Cloudy", 496 | "OriginCityName": "Rome", 497 | "AvgTicketPrice": 552.9173708459598, 498 | "DistanceMiles": 4806.775668847457, 499 | "FlightDelay": false, 500 | "DestWeather": "Clear", 501 | "Dest": "Luis Munoz Marin International Airport", 502 | "FlightDelayType": "No Delay", 503 | "OriginCountry": "IT", 504 | "dayOfWeek": 0, 505 | "DistanceKilometers": 7735.755582005642, 506 | "timestamp": "2019-09-16T17:42:53", 507 | "DestLocation": { 508 | "lat": "18.43939972", 509 | "lon": "-66.00180054" 510 | }, 511 | "DestAirportID": "SJU", 512 | "Carrier": "Logstash Airways", 513 | "Cancelled": false, 514 | "FlightTimeMin": 407.1450306318759, 515 | "Origin": "Ciampino___G. B. Pastine International Airport", 516 | "OriginLocation": { 517 | "lat": "41.7994", 518 | "lon": "12.5949" 519 | }, 520 | "DestRegion": "PR-U-A", 521 | "OriginAirportID": "RM12", 522 | "OriginRegion": "IT-62", 523 | "DestCityName": "San Juan", 524 | "FlightTimeHour": 6.7857505105312645, 525 | "FlightDelayMin": 0 526 | }, 527 | { 528 | "FlightNum": "YIPS2BZ", 529 | "DestCountry": "DE", 530 | "OriginWeather": "Thunder & Lightning", 531 | "OriginCityName": "Chengdu", 532 | "AvgTicketPrice": 566.4875569256166, 533 | "DistanceMiles": 4896.74792596565, 534 | "FlightDelay": false, 535 | "DestWeather": "Sunny", 536 | "Dest": "Cologne Bonn Airport", 537 | "FlightDelayType": "No Delay", 538 | "OriginCountry": "CN", 539 | "dayOfWeek": 0, 540 | "DistanceKilometers": 7880.551894165264, 541 | "timestamp": "2019-09-16T19:55:32", 542 | "DestLocation": { 543 | "lat": "50.86589813", 544 | "lon": "7.142739773" 545 | }, 546 | "DestAirportID": "CGN", 547 | "Carrier": "Kibana Airlines", 548 | "Cancelled": true, 549 | "FlightTimeMin": 656.7126578471053, 550 | "Origin": "Chengdu Shuangliu International Airport", 551 | "OriginLocation": { 552 | "lat": "30.57850075", 553 | "lon": "103.9469986" 554 | }, 555 | "DestRegion": "DE-NW", 556 | "OriginAirportID": "CTU", 557 | "OriginRegion": "SE-BD", 558 | "DestCityName": "Cologne", 559 | "FlightTimeHour": 10.945210964118422, 560 | "FlightDelayMin": 0 561 | }, 562 | { 563 | "FlightNum": "C7IBZ42", 564 | "DestCountry": "IT", 565 | "OriginWeather": "Thunder & Lightning", 566 | "OriginCityName": "Mexico City", 567 | "AvgTicketPrice": 989.9527866266118, 568 | "DistanceMiles": 6244.404143498341, 569 | "FlightDelay": false, 570 | "DestWeather": "Damaging Wind", 571 | "Dest": "Venice Marco Polo Airport", 572 | "FlightDelayType": "No Delay", 573 | "OriginCountry": "MX", 574 | "dayOfWeek": 0, 575 | "DistanceKilometers": 10049.394341914194, 576 | "timestamp": "2019-09-16T07:49:27", 577 | "DestLocation": { 578 | "lat": "45.505299", 579 | "lon": "12.3519" 580 | }, 581 | "DestAirportID": "VE05", 582 | "Carrier": "Logstash Airways", 583 | "Cancelled": true, 584 | "FlightTimeMin": 773.0303339933996, 585 | "Origin": "Licenciado Benito Juarez International Airport", 586 | "OriginLocation": { 587 | "lat": "19.4363", 588 | "lon": "-99.072098" 589 | }, 590 | "DestRegion": "IT-34", 591 | "OriginAirportID": "AICM", 592 | "OriginRegion": "MX-DIF", 593 | "DestCityName": "Venice", 594 | "FlightTimeHour": 12.883838899889993, 595 | "FlightDelayMin": 0 596 | }, 597 | { 598 | "FlightNum": "7TTZM4I", 599 | "DestCountry": "AR", 600 | "OriginWeather": "Rain", 601 | "OriginCityName": "Cleveland", 602 | "AvgTicketPrice": 569.6132552035547, 603 | "DistanceMiles": 5450.245542110189, 604 | "FlightDelay": true, 605 | "DestWeather": "Cloudy", 606 | "Dest": "Ministro Pistarini International Airport", 607 | "FlightDelayType": "NAS Delay", 608 | "OriginCountry": "US", 609 | "dayOfWeek": 0, 610 | "DistanceKilometers": 8771.31996172178, 611 | "timestamp": "2019-09-16T01:30:47", 612 | "DestLocation": { 613 | "lat": "-34.8222", 614 | "lon": "-58.5358" 615 | }, 616 | "DestAirportID": "EZE", 617 | "Carrier": "ES-Air", 618 | "Cancelled": false, 619 | "FlightTimeMin": 704.7169201324446, 620 | "Origin": "Cleveland Hopkins International Airport", 621 | "OriginLocation": { 622 | "lat": "41.4117012", 623 | "lon": "-81.84980011" 624 | }, 625 | "DestRegion": "SE-BD", 626 | "OriginAirportID": "CLE", 627 | "OriginRegion": "US-OH", 628 | "DestCityName": "Buenos Aires", 629 | "FlightTimeHour": 11.745282002207409, 630 | "FlightDelayMin": 30 631 | }, 632 | { 633 | "FlightNum": "CSW89S3", 634 | "DestCountry": "CN", 635 | "OriginWeather": "Hail", 636 | "OriginCityName": "Olenegorsk", 637 | "AvgTicketPrice": 277.4297073844173, 638 | "DistanceMiles": 4202.458848620224, 639 | "FlightDelay": false, 640 | "DestWeather": "Clear", 641 | "Dest": "Shanghai Pudong International Airport", 642 | "FlightDelayType": "No Delay", 643 | "OriginCountry": "RU", 644 | "dayOfWeek": 0, 645 | "DistanceKilometers": 6763.2019332738655, 646 | "timestamp": "2019-09-16T07:58:17", 647 | "DestLocation": { 648 | "lat": "31.14340019", 649 | "lon": "121.8050003" 650 | }, 651 | "DestAirportID": "PVG", 652 | "Carrier": "ES-Air", 653 | "Cancelled": false, 654 | "FlightTimeMin": 355.95799648809816, 655 | "Origin": "Olenya Air Base", 656 | "OriginLocation": { 657 | "lat": "68.15180206", 658 | "lon": "33.46390152" 659 | }, 660 | "DestRegion": "SE-BD", 661 | "OriginAirportID": "XLMO", 662 | "OriginRegion": "RU-MUR", 663 | "DestCityName": "Shanghai", 664 | "FlightTimeHour": 5.932633274801636, 665 | "FlightDelayMin": 0 666 | }, 667 | { 668 | "FlightNum": "RBFKZBX", 669 | "DestCountry": "IN", 670 | "OriginWeather": "Cloudy", 671 | "OriginCityName": "Casper", 672 | "AvgTicketPrice": 772.1008456460212, 673 | "DistanceMiles": 7507.304095087099, 674 | "FlightDelay": true, 675 | "DestWeather": "Clear", 676 | "Dest": "Indira Gandhi International Airport", 677 | "FlightDelayType": "Late Aircraft Delay", 678 | "OriginCountry": "US", 679 | "dayOfWeek": 0, 680 | "DistanceKilometers": 12081.834801603853, 681 | "timestamp": "2019-09-16T00:02:06", 682 | "DestLocation": { 683 | "lat": "28.5665", 684 | "lon": "77.103104" 685 | }, 686 | "DestAirportID": "DEL", 687 | "Carrier": "JetBeats", 688 | "Cancelled": false, 689 | "FlightTimeMin": 875.1146751002408, 690 | "Origin": "Casper-Natrona County International Airport", 691 | "OriginLocation": { 692 | "lat": "42.90800095", 693 | "lon": "-106.4639969" 694 | }, 695 | "DestRegion": "SE-BD", 696 | "OriginAirportID": "CPR", 697 | "OriginRegion": "US-WY", 698 | "DestCityName": "New Delhi", 699 | "FlightTimeHour": 14.585244585004013, 700 | "FlightDelayMin": 120 701 | }, 702 | { 703 | "FlightNum": "R43CELD", 704 | "DestCountry": "US", 705 | "OriginWeather": "Cloudy", 706 | "OriginCityName": "Erie", 707 | "AvgTicketPrice": 167.59992219374266, 708 | "DistanceMiles": 965.1786928006221, 709 | "FlightDelay": true, 710 | "DestWeather": "Clear", 711 | "Dest": "Wichita Mid Continent Airport", 712 | "FlightDelayType": "Carrier Delay", 713 | "OriginCountry": "US", 714 | "dayOfWeek": 0, 715 | "DistanceKilometers": 1553.3045381865245, 716 | "timestamp": "2019-09-16T01:08:20", 717 | "DestLocation": { 718 | "lat": "37.64989853", 719 | "lon": "-97.43309784" 720 | }, 721 | "DestAirportID": "ICT", 722 | "Carrier": "JetBeats", 723 | "Cancelled": false, 724 | "FlightTimeMin": 373.96688277078687, 725 | "Origin": "Erie International Tom Ridge Field", 726 | "OriginLocation": { 727 | "lat": "42.08312701", 728 | "lon": "-80.17386675" 729 | }, 730 | "DestRegion": "US-KS", 731 | "OriginAirportID": "ERI", 732 | "OriginRegion": "US-PA", 733 | "DestCityName": "Wichita", 734 | "FlightTimeHour": 6.232781379513114, 735 | "FlightDelayMin": 300 736 | }, 737 | { 738 | "FlightNum": "1TJWK8F", 739 | "DestCountry": "CA", 740 | "OriginWeather": "Clear", 741 | "OriginCityName": "Newark", 742 | "AvgTicketPrice": 253.21006490337038, 743 | "DistanceMiles": 328.5065863946441, 744 | "FlightDelay": true, 745 | "DestWeather": "Hail", 746 | "Dest": "Ottawa Macdonald-Cartier International Airport", 747 | "FlightDelayType": "NAS Delay", 748 | "OriginCountry": "US", 749 | "dayOfWeek": 0, 750 | "DistanceKilometers": 528.6801037747022, 751 | "timestamp": "2019-09-16T01:08:20", 752 | "DestLocation": { 753 | "lat": "45.32249832", 754 | "lon": "-75.66919708" 755 | }, 756 | "DestAirportID": "YOW", 757 | "Carrier": "ES-Air", 758 | "Cancelled": false, 759 | "FlightTimeMin": 130.66770029036172, 760 | "Origin": "Newark Liberty International Airport", 761 | "OriginLocation": { 762 | "lat": "40.69250107", 763 | "lon": "-74.16870117" 764 | }, 765 | "DestRegion": "CA-ON", 766 | "OriginAirportID": "EWR", 767 | "OriginRegion": "US-NJ", 768 | "DestCityName": "Ottawa", 769 | "FlightTimeHour": 2.177795004839362, 770 | "FlightDelayMin": 90 771 | }, 772 | { 773 | "FlightNum": "UDTSN13", 774 | "DestCountry": "JP", 775 | "OriginWeather": "Sunny", 776 | "OriginCityName": "Copenhagen", 777 | "AvgTicketPrice": 917.2476203642742, 778 | "DistanceMiles": 5354.622537746889, 779 | "FlightDelay": false, 780 | "DestWeather": "Damaging Wind", 781 | "Dest": "Itami Airport", 782 | "FlightDelayType": "No Delay", 783 | "OriginCountry": "DK", 784 | "dayOfWeek": 0, 785 | "DistanceKilometers": 8617.42965338773, 786 | "timestamp": "2019-09-16T07:48:35", 787 | "DestLocation": { 788 | "lat": "34.78549957", 789 | "lon": "135.4380035" 790 | }, 791 | "DestAirportID": "ITM", 792 | "Carrier": "JetBeats", 793 | "Cancelled": false, 794 | "FlightTimeMin": 574.4953102258486, 795 | "Origin": "Copenhagen Kastrup Airport", 796 | "OriginLocation": { 797 | "lat": "55.61790085", 798 | "lon": "12.65600014" 799 | }, 800 | "DestRegion": "SE-BD", 801 | "OriginAirportID": "CPH", 802 | "OriginRegion": "DK-84", 803 | "DestCityName": "Osaka", 804 | "FlightTimeHour": 9.574921837097476, 805 | "FlightDelayMin": 0 806 | }, 807 | { 808 | "FlightNum": "7Y08OAU", 809 | "DestCountry": "AT", 810 | "OriginWeather": "Heavy Fog", 811 | "OriginCityName": "Seattle", 812 | "AvgTicketPrice": 451.5911757026697, 813 | "DistanceMiles": 5403.40296642641, 814 | "FlightDelay": false, 815 | "DestWeather": "Heavy Fog", 816 | "Dest": "Vienna International Airport", 817 | "FlightDelayType": "No Delay", 818 | "OriginCountry": "US", 819 | "dayOfWeek": 0, 820 | "DistanceKilometers": 8695.934143600545, 821 | "timestamp": "2019-09-16T18:57:21", 822 | "DestLocation": { 823 | "lat": "48.11029816", 824 | "lon": "16.56970024" 825 | }, 826 | "DestAirportID": "VIE", 827 | "Carrier": "Logstash Airways", 828 | "Cancelled": false, 829 | "FlightTimeMin": 579.728942906703, 830 | "Origin": "Seattle Tacoma International Airport", 831 | "OriginLocation": { 832 | "lat": "47.44900131", 833 | "lon": "-122.3089981" 834 | }, 835 | "DestRegion": "AT-9", 836 | "OriginAirportID": "SEA", 837 | "OriginRegion": "US-WA", 838 | "DestCityName": "Vienna", 839 | "FlightTimeHour": 9.66214904844505, 840 | "FlightDelayMin": 0 841 | }, 842 | { 843 | "FlightNum": "MH65PPZ", 844 | "DestCountry": "FR", 845 | "OriginWeather": "Rain", 846 | "OriginCityName": "Berlin", 847 | "AvgTicketPrice": 307.0672008820741, 848 | "DistanceMiles": 529.8263707088325, 849 | "FlightDelay": false, 850 | "DestWeather": "Clear", 851 | "Dest": "Charles de Gaulle International Airport", 852 | "FlightDelayType": "No Delay", 853 | "OriginCountry": "DE", 854 | "dayOfWeek": 0, 855 | "DistanceKilometers": 852.6728907420354, 856 | "timestamp": "2019-09-16T13:18:25", 857 | "DestLocation": { 858 | "lat": "49.01279831", 859 | "lon": "2.549999952" 860 | }, 861 | "DestAirportID": "CDG", 862 | "Carrier": "Logstash Airways", 863 | "Cancelled": false, 864 | "FlightTimeMin": 50.15722886717855, 865 | "Origin": "Berlin-Tegel Airport", 866 | "OriginLocation": { 867 | "lat": "52.5597", 868 | "lon": "13.2877" 869 | }, 870 | "DestRegion": "FR-J", 871 | "OriginAirportID": "TXL", 872 | "OriginRegion": "DE-BE", 873 | "DestCityName": "Paris", 874 | "FlightTimeHour": 0.8359538144529759, 875 | "FlightDelayMin": 0 876 | }, 877 | { 878 | "FlightNum": "7SFSTEH", 879 | "DestCountry": "JP", 880 | "OriginWeather": "Thunder & Lightning", 881 | "OriginCityName": "Manchester", 882 | "AvgTicketPrice": 268.24159591388866, 883 | "DistanceMiles": 5900.673562063734, 884 | "FlightDelay": false, 885 | "DestWeather": "Rain", 886 | "Dest": "Narita International Airport", 887 | "FlightDelayType": "No Delay", 888 | "OriginCountry": "GB", 889 | "dayOfWeek": 0, 890 | "DistanceKilometers": 9496.213593065899, 891 | "timestamp": "2019-09-16T08:20:35", 892 | "DestLocation": { 893 | "lat": "35.76470184", 894 | "lon": "140.3860016" 895 | }, 896 | "DestAirportID": "NRT", 897 | "Carrier": "ES-Air", 898 | "Cancelled": false, 899 | "FlightTimeMin": 527.5674218369944, 900 | "Origin": "Manchester Airport", 901 | "OriginLocation": { 902 | "lat": "53.35369873", 903 | "lon": "-2.274950027" 904 | }, 905 | "DestRegion": "SE-BD", 906 | "OriginAirportID": "MAN", 907 | "OriginRegion": "GB-ENG", 908 | "DestCityName": "Tokyo", 909 | "FlightTimeHour": 8.792790363949907, 910 | "FlightDelayMin": 0 911 | }, 912 | { 913 | "FlightNum": "430NKQO", 914 | "DestCountry": "JP", 915 | "OriginWeather": "Rain", 916 | "OriginCityName": "Helsinki", 917 | "AvgTicketPrice": 975.8126321392289, 918 | "DistanceMiles": 4800.213800795046, 919 | "FlightDelay": false, 920 | "DestWeather": "Hail", 921 | "Dest": "Itami Airport", 922 | "FlightDelayType": "No Delay", 923 | "OriginCountry": "FI", 924 | "dayOfWeek": 0, 925 | "DistanceKilometers": 7725.195279026703, 926 | "timestamp": "2019-09-16T15:38:32", 927 | "DestLocation": { 928 | "lat": "34.78549957", 929 | "lon": "135.4380035" 930 | }, 931 | "DestAirportID": "ITM", 932 | "Carrier": "Kibana Airlines", 933 | "Cancelled": true, 934 | "FlightTimeMin": 386.2597639513352, 935 | "Origin": "Helsinki Vantaa Airport", 936 | "OriginLocation": { 937 | "lat": "60.31719971", 938 | "lon": "24.9633007" 939 | }, 940 | "DestRegion": "SE-BD", 941 | "OriginAirportID": "HEL", 942 | "OriginRegion": "FI-ES", 943 | "DestCityName": "Osaka", 944 | "FlightTimeHour": 6.437662732522253, 945 | "FlightDelayMin": 0 946 | }, 947 | { 948 | "FlightNum": "3YAQM9U", 949 | "DestCountry": "US", 950 | "OriginWeather": "Clear", 951 | "OriginCityName": "Phoenix", 952 | "AvgTicketPrice": 134.21454568995148, 953 | "DistanceMiles": 304.2189898030449, 954 | "FlightDelay": false, 955 | "DestWeather": "Clear", 956 | "Dest": "San Diego International Airport", 957 | "FlightDelayType": "No Delay", 958 | "OriginCountry": "US", 959 | "dayOfWeek": 0, 960 | "DistanceKilometers": 489.59300592559157, 961 | "timestamp": "2019-09-16T03:08:45", 962 | "DestLocation": { 963 | "lat": "32.73360062", 964 | "lon": "-117.1900024" 965 | }, 966 | "DestAirportID": "SAN", 967 | "Carrier": "JetBeats", 968 | "Cancelled": false, 969 | "FlightTimeMin": 24.47965029627958, 970 | "Origin": "Phoenix Sky Harbor International Airport", 971 | "OriginLocation": { 972 | "lat": "33.43429947", 973 | "lon": "-112.012001" 974 | }, 975 | "DestRegion": "US-CA", 976 | "OriginAirportID": "PHX", 977 | "OriginRegion": "US-AZ", 978 | "DestCityName": "San Diego", 979 | "FlightTimeHour": 0.4079941716046597, 980 | "FlightDelayMin": 0 981 | }, 982 | { 983 | "FlightNum": "HX0WBLI", 984 | "DestCountry": "IT", 985 | "OriginWeather": "Damaging Wind", 986 | "OriginCityName": "Chitose / Tomakomai", 987 | "AvgTicketPrice": 988.8975638746068, 988 | "DistanceMiles": 5650.511340218511, 989 | "FlightDelay": false, 990 | "DestWeather": "Sunny", 991 | "Dest": "Verona Villafranca Airport", 992 | "FlightDelayType": "No Delay", 993 | "OriginCountry": "JP", 994 | "dayOfWeek": 0, 995 | "DistanceKilometers": 9093.616522312619, 996 | "timestamp": "2019-09-16T01:16:59", 997 | "DestLocation": { 998 | "lat": "45.395699", 999 | "lon": "10.8885" 1000 | }, 1001 | "DestAirportID": "VR10", 1002 | "Carrier": "Kibana Airlines", 1003 | "Cancelled": false, 1004 | "FlightTimeMin": 568.3510326445387, 1005 | "Origin": "New Chitose Airport", 1006 | "OriginLocation": { 1007 | "lat": "42.77519989", 1008 | "lon": "141.6920013" 1009 | }, 1010 | "DestRegion": "IT-34", 1011 | "OriginAirportID": "CTS", 1012 | "OriginRegion": "SE-BD", 1013 | "DestCityName": "Verona", 1014 | "FlightTimeHour": 9.472517210742312, 1015 | "FlightDelayMin": 0 1016 | }, 1017 | { 1018 | "FlightNum": "BSVTVSA", 1019 | "DestCountry": "CH", 1020 | "OriginWeather": "Rain", 1021 | "OriginCityName": "Tulsa", 1022 | "AvgTicketPrice": 511.0672203518154, 1023 | "DistanceMiles": 5028.070244660456, 1024 | "FlightDelay": false, 1025 | "DestWeather": "Rain", 1026 | "Dest": "Zurich Airport", 1027 | "FlightDelayType": "No Delay", 1028 | "OriginCountry": "US", 1029 | "dayOfWeek": 0, 1030 | "DistanceKilometers": 8091.894679822838, 1031 | "timestamp": "2019-09-16T18:00:59", 1032 | "DestLocation": { 1033 | "lat": "47.464699", 1034 | "lon": "8.54917" 1035 | }, 1036 | "DestAirportID": "ZRH", 1037 | "Carrier": "Logstash Airways", 1038 | "Cancelled": false, 1039 | "FlightTimeMin": 425.8891936748862, 1040 | "Origin": "Tulsa International Airport", 1041 | "OriginLocation": { 1042 | "lat": "36.19839859", 1043 | "lon": "-95.88809967" 1044 | }, 1045 | "DestRegion": "CH-ZH", 1046 | "OriginAirportID": "TUL", 1047 | "OriginRegion": "US-OK", 1048 | "DestCityName": "Zurich", 1049 | "FlightTimeHour": 7.09815322791477, 1050 | "FlightDelayMin": 0 1051 | }, 1052 | { 1053 | "FlightNum": "OODIP58", 1054 | "DestCountry": "CN", 1055 | "OriginWeather": "Thunder & Lightning", 1056 | "OriginCityName": "Abu Dhabi", 1057 | "AvgTicketPrice": 252.9119662217096, 1058 | "DistanceMiles": 3032.4467769272865, 1059 | "FlightDelay": true, 1060 | "DestWeather": "Sunny", 1061 | "Dest": "Chengdu Shuangliu International Airport", 1062 | "FlightDelayType": "Late Aircraft Delay", 1063 | "OriginCountry": "AE", 1064 | "dayOfWeek": 0, 1065 | "DistanceKilometers": 4880.250025767267, 1066 | "timestamp": "2019-09-16T12:05:14", 1067 | "DestLocation": { 1068 | "lat": "30.57850075", 1069 | "lon": "103.9469986" 1070 | }, 1071 | "DestAirportID": "CTU", 1072 | "Carrier": "Kibana Airlines", 1073 | "Cancelled": false, 1074 | "FlightTimeMin": 490.3500017178178, 1075 | "Origin": "Abu Dhabi International Airport", 1076 | "OriginLocation": { 1077 | "lat": "24.43300056", 1078 | "lon": "54.65110016" 1079 | }, 1080 | "DestRegion": "SE-BD", 1081 | "OriginAirportID": "AUH", 1082 | "OriginRegion": "SE-BD", 1083 | "DestCityName": "Chengdu", 1084 | "FlightTimeHour": 8.172500028630298, 1085 | "FlightDelayMin": 165 1086 | } 1087 | ] 1088 | -------------------------------------------------------------------------------- /es/tests/test_0_fixtures.py: -------------------------------------------------------------------------------- 1 | import os 2 | import unittest 3 | 4 | from .fixtures.fixtures import ( 5 | create_alias, 6 | delete_alias, 7 | delete_index, 8 | import_data1, 9 | import_empty_index, 10 | import_flights, 11 | ) 12 | 13 | BASE_URL = "http://localhost:9200" 14 | 15 | 16 | class TestData(unittest.TestCase): 17 | def setUp(self): 18 | self.base_url = os.environ.get("ES_URI", BASE_URL) 19 | 20 | def test_1_data_flights(self): 21 | delete_index(self.base_url, "flights") 22 | import_flights(self.base_url) 23 | 24 | def test_2_data_data1(self): 25 | delete_index(self.base_url, "data1") 26 | import_data1(self.base_url) 27 | 28 | def test_3_data_empty_index(self): 29 | delete_index(self.base_url, "empty_index") 30 | import_empty_index(self.base_url) 31 | 32 | def test_4_alias_to_data1(self): 33 | alias_name = "alias_to_data1" 34 | delete_alias(self.base_url, alias_name, "data1") 35 | create_alias(self.base_url, alias_name, "data1") 36 | -------------------------------------------------------------------------------- /es/tests/test_dbapi.py: -------------------------------------------------------------------------------- 1 | import os 2 | import unittest 3 | from unittest.mock import patch 4 | 5 | from es.elastic.api import connect as elastic_connect, Type 6 | from es.exceptions import Error, NotSupportedError, OperationalError, ProgrammingError 7 | from es.opendistro.api import connect as open_connect 8 | 9 | 10 | def convert_bool(value: str) -> bool: 11 | return True if value == "True" else False 12 | 13 | 14 | class TestDBAPI(unittest.TestCase): 15 | def setUp(self): 16 | self.driver_name = os.environ.get("ES_DRIVER", "elasticsearch") 17 | self.host = os.environ.get("ES_HOST", "localhost") 18 | self.port = int(os.environ.get("ES_PORT", 9200)) 19 | self.scheme = os.environ.get("ES_SCHEME", "http") 20 | self.verify_certs = os.environ.get("ES_VERIFY_CERTS", False) 21 | self.user = os.environ.get("ES_USER", None) 22 | self.password = os.environ.get("ES_PASSWORD", None) 23 | self.v2 = bool(os.environ.get("ES_V2", False)) 24 | self.support_datetime_parse = convert_bool( 25 | os.environ.get("ES_SUPPORT_DATETIME_PARSE", "True") 26 | ) 27 | 28 | if self.driver_name == "elasticsearch": 29 | self.connect_func = elastic_connect 30 | else: 31 | self.connect_func = open_connect 32 | self.conn = self.connect_func( 33 | host=self.host, 34 | port=self.port, 35 | scheme=self.scheme, 36 | verify_certs=self.verify_certs, 37 | user=self.user, 38 | password=self.password, 39 | v2=self.v2, 40 | ) 41 | self.cursor = self.conn.cursor() 42 | 43 | def tearDown(self): 44 | self.conn.close() 45 | 46 | def test_connect_failed(self): 47 | """ 48 | DBAPI: Test connection failed 49 | """ 50 | conn = self.connect_func(host="unknown") 51 | curs = conn.cursor() 52 | with self.assertRaises(OperationalError): 53 | curs.execute("select Carrier from flights").fetchall() 54 | conn.close() 55 | 56 | def test_close(self): 57 | """ 58 | DBAPI: Test connection failed 59 | """ 60 | conn = self.connect_func(host="localhost") 61 | conn.close() 62 | with self.assertRaises(Error): 63 | conn.close() 64 | 65 | def test_execute_fetchall(self): 66 | """ 67 | DBAPI: Test execute and fetchall 68 | """ 69 | rows = self.cursor.execute("select Carrier from flights").fetchall() 70 | self.assertEqual(len(rows), 31) 71 | 72 | def test_execute_on_connect(self): 73 | """ 74 | DBAPI: Test execute, fetchall on connect 75 | """ 76 | rows = self.conn.execute("select Carrier from flights").fetchall() 77 | self.assertEqual(len(rows), 31) 78 | 79 | def test_commit_executes(self): 80 | """ 81 | DBAPI: Test commit method exists 82 | """ 83 | self.conn.commit() 84 | 85 | def test_executemany_not_supported(self): 86 | """ 87 | DBAPI: Test executemany not supported 88 | """ 89 | with self.assertRaises(NotSupportedError): 90 | self.cursor.executemany("select Carrier from flights") 91 | 92 | def test_execute_fetchmany(self): 93 | """ 94 | DBAPI: Test execute and fectchmany 95 | """ 96 | rows = self.cursor.execute("select Carrier from flights").fetchmany(2) 97 | self.assertEquals(len(rows), 2) 98 | 99 | def test_execute_fetchone(self): 100 | """ 101 | DBAPI: Test execute and fectchone 102 | """ 103 | rows = self.cursor.execute("select Carrier from flights").fetchone() 104 | self.assertEquals(len(rows), 1) 105 | 106 | def test_execute_empty_results(self): 107 | """ 108 | DBAPI: Test execute query with no results 109 | """ 110 | rows = self.cursor.execute( 111 | "select Carrier from flights where Carrier='NORESULT'" 112 | ).fetchall() 113 | self.assertEquals(len(rows), 0) 114 | 115 | count = self.cursor.execute( 116 | "select Carrier from flights where Carrier='NORESULT'" 117 | ).rowcount 118 | self.assertEquals(count, 0) 119 | 120 | def test_execute_rowcount(self): 121 | """ 122 | DBAPI: Test execute and rowcount 123 | """ 124 | count = self.cursor.execute("select Carrier from flights LIMIT 10").rowcount 125 | self.assertEquals(count, 10) 126 | 127 | def test_execute_wrong_table(self): 128 | """ 129 | DBAPI: Test execute select with wrong table 130 | """ 131 | with self.assertRaises(ProgrammingError): 132 | self.cursor.execute("select Carrier from no_table LIMIT 10").rowcount 133 | 134 | def test_execute_select_all(self): 135 | """ 136 | DBAPI: Test execute select all (*) 137 | """ 138 | rows = self.cursor.execute("select * from flights LIMIT 10").fetchall() 139 | # Make sure we have a list of tuples 140 | self.assertEqual(type(rows), type(list())) 141 | self.assertEqual(type(rows[0]), type(tuple())) 142 | self.assertEquals(len(rows), 10) 143 | 144 | def test_boolean_description(self): 145 | """ 146 | DBAPI: Test boolean description 147 | """ 148 | rows = self.cursor.execute("select Cancelled from flights LIMIT 1") 149 | self.assertEquals( 150 | rows.description, 151 | [("Cancelled", Type.BOOLEAN, None, None, None, None, True)], 152 | ) 153 | 154 | def test_number_description(self): 155 | """ 156 | DBAPI: Test number description 157 | """ 158 | rows = self.cursor.execute("select FlightDelayMin from flights LIMIT 1") 159 | self.assertEquals( 160 | rows.description, 161 | [("FlightDelayMin", Type.NUMBER, None, None, None, None, True)], 162 | ) 163 | 164 | def test_string_description(self): 165 | """ 166 | DBAPI: Test string description 167 | """ 168 | rows = self.cursor.execute("select DestCountry from flights LIMIT 1") 169 | self.assertEquals( 170 | rows.description, 171 | [("DestCountry", Type.STRING, None, None, None, None, True)], 172 | ) 173 | 174 | def test_datetime_description(self): 175 | """ 176 | DBAPI: Test datetime description 177 | """ 178 | rows = self.cursor.execute("select timestamp from flights LIMIT 1") 179 | self.assertEquals( 180 | rows.description, 181 | [("timestamp", Type.DATETIME, None, None, None, None, True)], 182 | ) 183 | 184 | def test_simple_group_by(self): 185 | """ 186 | DBAPI: Test simple group by 187 | """ 188 | if self.v2: 189 | group_by_column = "Carrier" 190 | else: 191 | group_by_column = "Carrier.keyword" 192 | rows = self.cursor.execute( 193 | f"select COUNT(*) as c, {group_by_column} " 194 | f"from flights GROUP BY {group_by_column}" 195 | ).fetchall() 196 | # poor assertion because that is loaded async 197 | self.assertEqual(len(rows), 4) 198 | 199 | @patch("elasticsearch.Elasticsearch.__init__") 200 | def test_auth(self, mock_elasticsearch): 201 | """ 202 | DBAPI: test Elasticsearch is called with user password 203 | """ 204 | mock_elasticsearch.return_value = None 205 | self.connect_func( 206 | host="localhost", scheme="http", port=9200, user="user", password="password" 207 | ) 208 | mock_elasticsearch.assert_called_once_with( 209 | "http://localhost:9200/", http_auth=("user", "password") 210 | ) 211 | 212 | @patch("elasticsearch.Elasticsearch.__init__") 213 | def test_https(self, mock_elasticsearch): 214 | """ 215 | DBAPI: test Elasticsearch is called with https 216 | """ 217 | mock_elasticsearch.return_value = None 218 | self.connect_func( 219 | host="localhost", 220 | user="user", 221 | password="password", 222 | scheme="https", 223 | port=9200, 224 | ) 225 | mock_elasticsearch.assert_called_once_with( 226 | "https://localhost:9200/", http_auth=("user", "password") 227 | ) 228 | 229 | def test_simple_search_with_time_zone(self): 230 | """ 231 | DBAPI: Test simple search with time zone 232 | UTC -> CST 233 | 2019-10-13T00:00:00.000Z => 2019-10-13T08:00:00.000+08:00 234 | 2019-10-13T00:00:01.000Z => 2019-10-13T08:01:00.000+08:00 235 | 2019-10-13T00:00:02.000Z => 2019-10-13T08:02:00.000+08:00 236 | """ 237 | 238 | if not self.support_datetime_parse: 239 | return 240 | 241 | conn = self.connect_func( 242 | host=self.host, 243 | port=self.port, 244 | scheme=self.scheme, 245 | verify_certs=self.verify_certs, 246 | user=self.user, 247 | password=self.password, 248 | v2=self.v2, 249 | time_zone="Asia/Shanghai", 250 | ) 251 | cursor = conn.cursor() 252 | pattern = "yyyy-MM-dd HH:mm:ss" 253 | sql = f""" 254 | SELECT timestamp FROM data1 255 | WHERE timestamp >= DATETIME_PARSE('2019-10-13 00:08:00', '{pattern}') 256 | """ 257 | 258 | rows = cursor.execute(sql).fetchall() 259 | self.assertEqual(len(rows), 3) 260 | 261 | def test_simple_search_without_time_zone(self): 262 | """ 263 | DBAPI: Test simple search without time zone 264 | """ 265 | 266 | if not self.support_datetime_parse: 267 | return 268 | 269 | conn = self.connect_func( 270 | host=self.host, 271 | port=self.port, 272 | scheme=self.scheme, 273 | verify_certs=self.verify_certs, 274 | user=self.user, 275 | password=self.password, 276 | v2=self.v2, 277 | ) 278 | cursor = conn.cursor() 279 | pattern = "yyyy-MM-dd HH:mm:ss" 280 | sql = f""" 281 | SELECT * FROM data1 282 | WHERE timestamp >= DATETIME_PARSE('2019-10-13 08:00:00', '{pattern}') 283 | """ 284 | 285 | rows = cursor.execute(sql).fetchall() 286 | self.assertEqual(len(rows), 0) 287 | -------------------------------------------------------------------------------- /es/tests/test_sqlalchemy.py: -------------------------------------------------------------------------------- 1 | import os 2 | from typing import List 3 | import unittest 4 | from unittest.mock import Mock, patch 5 | 6 | from es.elastic.sqlalchemy import ESDialect as ElasticDialect 7 | from es.exceptions import DatabaseError 8 | from es.opendistro.sqlalchemy import ESDialect as OpenDistroDialect 9 | from es.tests.fixtures.fixtures import data1_columns, flights_columns 10 | from sqlalchemy import func, inspect, select 11 | from sqlalchemy.engine import create_engine 12 | from sqlalchemy.engine.reflection import Inspector 13 | from sqlalchemy.engine.url import URL 14 | from sqlalchemy.exc import ProgrammingError 15 | from sqlalchemy.schema import MetaData, Table 16 | 17 | 18 | class MockCredentials: 19 | def __init__(self, access_key: str, secret_key: str, token: str) -> None: 20 | self.access_key = access_key 21 | self.secret_key = secret_key 22 | self.token = token 23 | 24 | 25 | class TestSQLAlchemy(unittest.TestCase): 26 | def setUp(self): 27 | self.driver_name = os.environ.get("ES_DRIVER", "elasticsearch") 28 | host = os.environ.get("ES_HOST", "localhost") 29 | port = int(os.environ.get("ES_PORT", 9200)) 30 | scheme = os.environ.get("ES_SCHEME", "http") 31 | verify_certs = os.environ.get("ES_VERIFY_CERTS", "False") 32 | user = os.environ.get("ES_USER", None) 33 | password = os.environ.get("ES_PASSWORD", None) 34 | self.v2 = bool(os.environ.get("ES_V2", False)) 35 | 36 | uri = URL( 37 | f"{self.driver_name}+{scheme}", 38 | user, 39 | password, 40 | host, 41 | port, 42 | None, 43 | {"verify_certs": str(verify_certs), "v2": self.v2}, 44 | ) 45 | self.engine = create_engine(uri) 46 | self.connection = self.engine.connect() 47 | self.table_flights = Table("flights", MetaData(bind=self.engine), autoload=True) 48 | 49 | def make_columns_compliant(self, columns: List[str]) -> List[str]: 50 | """ 51 | Opendistro v1 and v2 return a different list of columns. 52 | keyword fields are not recognised on v2. 53 | 54 | :param columns: A List of column names 55 | :return: A list of expected column names for a certain opendistro version 56 | """ 57 | return [ 58 | column 59 | for column in columns 60 | if self.v2 and not column.endswith(".keyword") or not self.v2 61 | ] 62 | 63 | def test_simple_query(self): 64 | """ 65 | SQLAlchemy: Test simple query 66 | """ 67 | rows = self.connection.execute("select Carrier from flights").fetchall() 68 | self.assertGreater(len(rows), 1) 69 | 70 | def test_execute_wrong_table(self): 71 | """ 72 | SQLAlchemy: Test execute select with wrong table 73 | """ 74 | with self.assertRaises(ProgrammingError): 75 | self.connection.execute("select Carrier from no_table LIMIT 10").fetchall() 76 | 77 | def test_reflection_get_tables(self): 78 | """ 79 | SQLAlchemy: Test reflection get_tables 80 | """ 81 | metadata = MetaData() 82 | metadata.reflect(bind=self.engine) 83 | tables = [str(table) for table in metadata.sorted_tables] 84 | self.assertIn("flights", tables) 85 | 86 | def test_has_table(self): 87 | """ 88 | SQLAlchemy: Test has_table 89 | """ 90 | self.assertTrue(self.engine.has_table("flights")) 91 | 92 | def test_get_schema_names(self): 93 | """ 94 | SQLAlchemy: Test get schema names 95 | """ 96 | insp = inspect(self.engine) 97 | self.assertEqual(insp.get_schema_names(), ["default"]) 98 | 99 | def test_reflection_get_columns(self): 100 | """ 101 | SQLAlchemy: Test get_columns 102 | """ 103 | metadata = MetaData() 104 | metadata.reflect(bind=self.engine) 105 | source_cols = [c.name for c in metadata.tables["flights"].c] 106 | self.assertEqual(self.make_columns_compliant(flights_columns), source_cols) 107 | 108 | def test_get_columns_exclude_arrays(self): 109 | """ 110 | SQLAlchemy: Test get_columns exclude arrays (elastic only) 111 | """ 112 | if self.driver_name == "odelasticsearch": 113 | return 114 | metadata = MetaData() 115 | metadata.reflect(bind=self.engine) 116 | source_cols = [c.name for c in metadata.tables["data1"].c] 117 | self.assertEqual(data1_columns, source_cols) 118 | 119 | def test_get_view_names(self): 120 | """ 121 | SQLAlchemy: Test get_view_names to verify alias is returned 122 | """ 123 | inspector = Inspector.from_engine(self.engine) 124 | if self.v2: 125 | tables = inspector.get_table_names("default1") 126 | self.assertIn("alias_to_data1", tables) 127 | else: 128 | views = inspector.get_view_names("default1") 129 | self.assertEqual(views, ["alias_to_data1"]) 130 | 131 | def test_get_alias_columns(self): 132 | """ 133 | SQLAlchemy: Test get_view_names to verify alias is returned 134 | """ 135 | inspector = Inspector.from_engine(self.engine) 136 | alias_columns = inspector.get_columns("alias_to_data1") 137 | index_columns = inspector.get_columns("data1") 138 | for i, alias_column in enumerate(alias_columns): 139 | self.assertEqual(alias_column["name"], index_columns[i]["name"]) 140 | self.assertEqual(type(alias_column["type"]), type(index_columns[i]["type"])) 141 | 142 | def test_get_columns_exclude_geo_point(self): 143 | """ 144 | SQLAlchemy: Test get_columns exclude geo point (odelasticsearch only) 145 | """ 146 | if self.driver_name == "elasticsearch": 147 | return 148 | metadata = MetaData() 149 | metadata.reflect(bind=self.engine) 150 | source_cols = [c.name for c in metadata.tables["data1"].c] 151 | expected_columns = [ 152 | "field_array", 153 | "field_array.keyword", 154 | "field_boolean", 155 | "field_float", 156 | "field_nested.c1", 157 | "field_nested.c1.keyword", 158 | "field_nested.c2", 159 | "field_number", 160 | "field_str", 161 | "field_str.keyword", 162 | "timestamp", 163 | ] 164 | self.assertEqual(source_cols, self.make_columns_compliant(expected_columns)) 165 | 166 | def test_select_count(self): 167 | """ 168 | SQLAlchemy: Test select all 169 | """ 170 | count = select([func.count("*")], from_obj=self.table_flights).scalar() 171 | # insert data delays let's assert we have something there 172 | self.assertGreater(count, 1) 173 | 174 | @patch("elasticsearch.Elasticsearch.__init__") 175 | def test_auth(self, mock_elasticsearch): 176 | """ 177 | SQLAlchemy: test Elasticsearch is called with user password 178 | """ 179 | mock_elasticsearch.return_value = None 180 | self.engine = create_engine( 181 | "elasticsearch+http://user:password@localhost:9200/" 182 | ) 183 | self.connection = self.engine.connect() 184 | mock_elasticsearch.assert_called_once_with( 185 | "http://localhost:9200/", http_auth=("user", "password") 186 | ) 187 | 188 | @patch("requests_aws4auth.AWS4Auth.__init__") 189 | def test_opendistro_aws_auth(self, mock_aws4auth): 190 | """ 191 | SQLAlchemy: test Elasticsearch is called AWS4Auth 192 | """ 193 | if self.driver_name == "odelasticsearch": 194 | 195 | mock_aws4auth.return_value = None 196 | self.engine = create_engine( 197 | "odelasticsearch+http://aws_access_key_x:aws_secret_key_y@" 198 | "localhost:9200/?aws_keys=1&aws_region=us-west-2" 199 | ) 200 | self.connection = self.engine.connect() 201 | mock_aws4auth.assert_called_once_with( 202 | "aws_access_key_x", "aws_secret_key_y", "us-west-2", "es" 203 | ) 204 | 205 | @patch("requests_aws4auth.AWS4Auth.__init__") 206 | def test_opendistro_aws_profile(self, mock_aws4auth): 207 | """ 208 | SQLAlchemy: test Elasticsearch is called AWS4Auth 209 | """ 210 | if self.driver_name != "odelasticsearch": 211 | return 212 | 213 | from boto3.session import Session 214 | 215 | mock_get_credentials = Session.get_credentials = Mock() 216 | mock_get_credentials.return_value = MockCredentials( 217 | access_key="aws_access_key_x", 218 | secret_key="aws_secret_key_y", 219 | token="token_z", 220 | ) 221 | mock_aws4auth.return_value = None 222 | self.engine = create_engine( 223 | "odelasticsearch+http://localhost:9200/?aws_profile=us-west-2" 224 | ) 225 | self.connection = self.engine.connect() 226 | mock_aws4auth.assert_called_once_with( 227 | "aws_access_key_x", 228 | "aws_secret_key_y", 229 | "us-west-2", 230 | "es", 231 | session_token="token_z", 232 | ) 233 | 234 | @patch("elasticsearch.Elasticsearch.__init__") 235 | def test_connection_https_and_auth(self, mock_elasticsearch): 236 | """ 237 | SQLAlchemy: test Elasticsearch is called with https and param 238 | """ 239 | mock_elasticsearch.return_value = None 240 | self.engine = create_engine( 241 | "elasticsearch+https://user:password@localhost:9200/" 242 | ) 243 | self.connection = self.engine.connect() 244 | mock_elasticsearch.assert_called_once_with( 245 | "https://localhost:9200/", http_auth=("user", "password") 246 | ) 247 | 248 | @patch("elasticsearch.Elasticsearch.__init__") 249 | def test_connection_https_and_params(self, mock_elasticsearch): 250 | """ 251 | SQLAlchemy: test Elasticsearch is called with https and param 252 | """ 253 | mock_elasticsearch.return_value = None 254 | self.engine = create_engine( 255 | "elasticsearch+https://localhost:9200/" 256 | "?verify_certs=False" 257 | "&use_ssl=False" 258 | ) 259 | self.connection = self.engine.connect() 260 | mock_elasticsearch.assert_called_once_with( 261 | "https://localhost:9200/", verify_certs=False, use_ssl=False 262 | ) 263 | 264 | @patch("elasticsearch.Elasticsearch.__init__") 265 | def test_connection_params(self, mock_elasticsearch): 266 | """ 267 | SQLAlchemy: test Elasticsearch is called with advanced config params 268 | """ 269 | mock_elasticsearch.return_value = None 270 | self.engine = create_engine( 271 | "elasticsearch+http://localhost:9200/" 272 | "?http_compress=True&maxsize=100&timeout=3" 273 | ) 274 | self.connection = self.engine.connect() 275 | mock_elasticsearch.assert_called_once_with( 276 | "http://localhost:9200/", http_compress=True, maxsize=100, timeout=3 277 | ) 278 | 279 | @patch("elasticsearch.Elasticsearch.__init__") 280 | def test_connection_params_value_error(self, mock_elasticsearch): 281 | """ 282 | SQLAlchemy: test Elasticsearch with param value error 283 | """ 284 | mock_elasticsearch.return_value = None 285 | with self.assertRaises(ValueError): 286 | self.engine = create_engine( 287 | "elasticsearch+http://localhost:9200/" "?http_compress=cena" 288 | ) 289 | 290 | @patch("elasticsearch.Elasticsearch.__init__") 291 | def test_connection_sniff(self, mock_elasticsearch): 292 | """ 293 | SQLAlchemy: test Elasticsearch is called for multiple hosts 294 | """ 295 | mock_elasticsearch.return_value = None 296 | self.engine = create_engine( 297 | "elasticsearch+http://localhost:9200/" 298 | "?sniff_on_start=True" 299 | "&sniff_on_connection_fail=True" 300 | "&sniffer_timeout=3" 301 | "&sniff_timeout=4" 302 | "&max_retries=10" 303 | "&retry_on_timeout=True" 304 | ) 305 | self.connection = self.engine.connect() 306 | mock_elasticsearch.assert_called_once_with( 307 | "http://localhost:9200/", 308 | sniff_on_start=True, 309 | sniff_on_connection_fail=True, 310 | sniffer_timeout=3, 311 | sniff_timeout=4, 312 | max_retries=10, 313 | retry_on_timeout=True, 314 | ) 315 | 316 | def test_ping(self): 317 | conn = self.engine.raw_connection() 318 | self.engine.dialect.do_ping(conn) 319 | 320 | def test_opendistro_ping_failed(self): 321 | if self.driver_name != "odelasticsearch": 322 | return 323 | from elasticsearch.exceptions import ConnectionError 324 | 325 | with patch("elasticsearch.Elasticsearch.ping") as mock_ping: 326 | mock_ping.side_effect = ConnectionError() 327 | conn = self.engine.raw_connection() 328 | with self.assertRaises(DatabaseError): 329 | self.engine.dialect.do_ping(conn) 330 | 331 | 332 | class TestQuote(unittest.TestCase): 333 | """ 334 | Test quoting identifiers in ES and OD. 335 | """ 336 | 337 | def test_elastic(self) -> None: 338 | assert ( 339 | ElasticDialect.preparer(dialect=ElasticDialect()).quote("DATE(123)") 340 | == '"DATE(123)"' 341 | ) 342 | 343 | def test_opendistro(self) -> None: 344 | assert ( 345 | OpenDistroDialect.preparer(dialect=OpenDistroDialect()).quote("DATE(123)") 346 | == "`DATE(123)`" 347 | ) 348 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | black==22.3.0 2 | coverage==6.3.2 3 | flake8==4.0.1 4 | flake8-commas==2.1.0 5 | flake8-import-order==0.18.1 6 | nose==1.3.7 7 | pip-tools==3.6.0 8 | pre-commit==1.17.0 9 | twine==2.0.0 10 | readme_renderer==24.0 11 | mypy==0.790 12 | requests-aws4auth==1.0.1 13 | boto3==1.16.63 14 | pytest==7.2.1 15 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # 2 | # This file is autogenerated by pip-compile 3 | # To update, run: 4 | # 5 | # pip-compile 6 | # 7 | certifi==2021.10.8 8 | # via elasticsearch 9 | elasticsearch==7.13.4 10 | # via elasticsearch-dbapi (setup.py) 11 | greenlet==1.0.0 12 | # via sqlalchemy 13 | importlib-metadata==4.0.0 14 | # via sqlalchemy 15 | packaging==21.3 16 | # via elasticsearch-dbapi (setup.py) 17 | pyparsing==2.4.7 18 | # via packaging 19 | sqlalchemy==1.4.9 20 | # via elasticsearch-dbapi (setup.py) 21 | typing-extensions==3.7.4.3 22 | # via importlib-metadata 23 | urllib3==1.26.5 24 | # via elasticsearch 25 | zipp==3.4.1 26 | # via importlib-metadata 27 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = elasticsearch-dbapi 3 | summary = A DBAPI and SQLAlchemy dialect for Elasticsearch 4 | description-file = README.md 5 | author = Preset Inc. 6 | author-email = daniel@preset.io 7 | license = Apache License, Version 2.0 8 | 9 | [mypy] 10 | disallow_any_generics = true 11 | ignore_missing_imports = true 12 | no_implicit_optional = true 13 | warn_unused_ignores = true 14 | 15 | [mypy-es.elastic.*] 16 | check_untyped_defs = true 17 | disallow_untyped_calls = true 18 | disallow_untyped_defs = true 19 | warn_unused_ignores = false 20 | 21 | [mypy-es.opendistro.*] 22 | check_untyped_defs = true 23 | disallow_untyped_calls = true 24 | disallow_untyped_defs = true 25 | warn_unused_ignores = false 26 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import io 2 | import os 3 | 4 | from setuptools import find_packages, setup 5 | 6 | VERSION = "0.2.11" 7 | BASE_DIR = os.path.abspath(os.path.dirname(__file__)) 8 | 9 | with io.open("README.md", "r", encoding="utf-8") as f: 10 | long_description = f.read() 11 | 12 | setup( 13 | name="elasticsearch-dbapi", 14 | description=("A DBAPI and SQLAlchemy dialect for Elasticsearch"), 15 | long_description=long_description, 16 | long_description_content_type="text/markdown", 17 | version=VERSION, 18 | packages=find_packages(), 19 | include_package_data=True, 20 | zip_safe=False, 21 | entry_points={ 22 | "sqlalchemy.dialects": [ 23 | "elasticsearch = es.elastic.sqlalchemy:ESHTTPDialect", 24 | "elasticsearch.http = es.elastic.sqlalchemy:ESHTTPDialect", 25 | "elasticsearch.https = es.elastic.sqlalchemy:ESHTTPSDialect", 26 | "odelasticsearch = es.opendistro.sqlalchemy:ESHTTPDialect", 27 | "odelasticsearch.http = es.opendistro.sqlalchemy:ESHTTPDialect", 28 | "odelasticsearch.https = es.opendistro.sqlalchemy:ESHTTPSDialect", 29 | ] 30 | }, 31 | install_requires=["elasticsearch>7, <7.14", "packaging>=21.0", "sqlalchemy"], 32 | extras_require={"opendistro": ["requests_aws4auth", "boto3"]}, 33 | author="Preset Inc.", 34 | author_email="daniel@preset.io", 35 | url="http://preset.io", 36 | download_url="https://github.com/preset-io/elasticsearch-dbapi/releases/tag/" 37 | + VERSION, 38 | classifiers=[ 39 | "Programming Language :: Python :: 3.6", 40 | "Programming Language :: Python :: 3.7", 41 | "Programming Language :: Python :: 3.8", 42 | "Programming Language :: Python :: 3.9", 43 | ], 44 | tests_require=["nose>=1.0"], 45 | test_suite="nose.collector", 46 | ) 47 | -------------------------------------------------------------------------------- /utils/export.py: -------------------------------------------------------------------------------- 1 | # Simple util to export indexes from Elasticsearch 2 | 3 | import json 4 | import requests 5 | 6 | index = "kibana_sample_data_flights" 7 | headers = {"Content-Type": "application/json"} 8 | base_url = "http://localhost:9200" 9 | url = f"{base_url}/{index}/_search?size=100" 10 | file_path = "kibana_sample_data_flights.json" 11 | r = requests.get(url, headers=headers) 12 | data = [doc["_source"] for doc in r.json()["hits"]["hits"]] 13 | 14 | fd = open(file_path, "w") 15 | json.dump(data, fd) 16 | fd.close() 17 | --------------------------------------------------------------------------------