|
| 1 | +# Licensed to Elasticsearch B.V. under one or more contributor |
| 2 | +# license agreements. See the NOTICE file distributed with |
| 3 | +# this work for additional information regarding copyright |
| 4 | +# ownership. Elasticsearch B.V. licenses this file to you under |
| 5 | +# the Apache License, Version 2.0 (the "License"); you may |
| 6 | +# not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | + |
| 18 | +""" |
| 19 | +Example ``Document`` with point datatype. |
| 20 | +
|
| 21 | +In the ``Place`` class we index the place's location as coordinates |
| 22 | +to allow spatial queries and distance-based searches. |
| 23 | +""" |
| 24 | + |
| 25 | +import asyncio |
| 26 | +import os |
| 27 | +from typing import TYPE_CHECKING, Any, Optional |
| 28 | + |
| 29 | +import elasticsearch_dsl as dsl |
| 30 | + |
| 31 | + |
| 32 | +class Place(dsl.AsyncDocument): |
| 33 | + if TYPE_CHECKING: |
| 34 | + # definitions here help type checkers understand additional arguments |
| 35 | + # that are allowed in the constructor |
| 36 | + _id: Optional[int] = dsl.mapped_field(default=None) |
| 37 | + |
| 38 | + location: Any = dsl.mapped_field(dsl.Point(), default="") |
| 39 | + |
| 40 | + class Index: |
| 41 | + name = "test-point" |
| 42 | + |
| 43 | + |
| 44 | +async def main() -> None: |
| 45 | + # initiate the default connection to elasticsearch |
| 46 | + dsl.async_connections.create_connection(hosts=[os.environ["ELASTICSEARCH_URL"]]) |
| 47 | + |
| 48 | + # create the empty index |
| 49 | + await Place.init() |
| 50 | + |
| 51 | + # index some sample data |
| 52 | + for id, location in enumerate( |
| 53 | + [ |
| 54 | + {"type": "Point", "coordinates": [5.43, 32.11]}, |
| 55 | + "POINT (-71.34 41.12)", |
| 56 | + {"x": -75.22, "y": -3.14}, |
| 57 | + [19.12, 52], |
| 58 | + "84.12,-54.24", |
| 59 | + ], |
| 60 | + ): |
| 61 | + await Place(_id=id, location=location).save() |
| 62 | + |
| 63 | + # refresh index manually to make changes live |
| 64 | + await Place._index.refresh() |
| 65 | + |
| 66 | + # close the connection |
| 67 | + await dsl.async_connections.get_connection().close() |
| 68 | + |
| 69 | + |
| 70 | +if __name__ == "__main__": |
| 71 | + asyncio.run(main()) |
0 commit comments