├── .gitignore ├── gradle.properties ├── config └── elastic.importorder ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src ├── test │ ├── resources │ │ └── rest-api-spec │ │ │ └── test │ │ │ ├── .DS_Store │ │ │ └── GeoExtension │ │ │ └── .DS_Store │ └── java │ │ └── org │ │ └── opendatasoft │ │ └── elasticsearch │ │ └── plugin │ │ └── GeoUtilsTests.java ├── main │ ├── java │ │ └── org │ │ │ └── opendatasoft │ │ │ └── elasticsearch │ │ │ ├── .DS_Store │ │ │ ├── search │ │ │ └── aggregations │ │ │ │ └── bucket │ │ │ │ └── geoshape │ │ │ │ ├── GeoShape.java │ │ │ │ ├── GeoShapeAggregatorSupplier.java │ │ │ │ ├── GeoShapeAggregatorFactory.java │ │ │ │ ├── GeoShapeBuilder.java │ │ │ │ ├── InternalGeoShape.java │ │ │ │ └── GeoShapeAggregator.java │ │ │ ├── plugin │ │ │ ├── GeoExtensionPlugin.java │ │ │ └── GeoUtils.java │ │ │ ├── script │ │ │ └── ScriptGeoSimplify.java │ │ │ └── ingest │ │ │ └── GeoExtensionProcessor.java │ └── main.iml └── yamlRestTest │ ├── resources │ └── rest-api-spec │ │ └── test │ │ └── GeoExtension │ │ ├── 10_basic.yml │ │ ├── 50_invalid_polygon.yml │ │ ├── 40_geoshape_aggregation.yml │ │ ├── 30_simplify_script.yml │ │ └── 20_geo_ingest_processor.yml │ └── java │ └── org │ └── opendatasoft │ └── elasticsearch │ └── RestApiYamlIT.java ├── docker └── Dockerfile ├── CHANGELOG.md ├── docker-compose.yml ├── .github └── workflows │ ├── build.yaml │ └── release.yaml ├── gradlew.bat ├── gradlew ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | .DS_Store 3 | .gradle/ 4 | .idea/ 5 | build/ 6 | .vscode/ 7 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | elastic_version = 8.19.6 2 | plugin_version = 8.19.6.0 3 | hamcrest_version = 2.1 4 | junit_version = 4.13.2 5 | -------------------------------------------------------------------------------- /config/elastic.importorder: -------------------------------------------------------------------------------- 1 | #Eclipse configuration for import order for Elasticsearch 2 | 0= 3 | 1=com 4 | 2=org 5 | 3=java 6 | 4=javax 7 | 5=\# 8 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/opendatasoft/elasticsearch-plugin-geoshape/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/test/resources/rest-api-spec/test/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/opendatasoft/elasticsearch-plugin-geoshape/HEAD/src/test/resources/rest-api-spec/test/.DS_Store -------------------------------------------------------------------------------- /src/main/java/org/opendatasoft/elasticsearch/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/opendatasoft/elasticsearch-plugin-geoshape/HEAD/src/main/java/org/opendatasoft/elasticsearch/.DS_Store -------------------------------------------------------------------------------- /src/test/resources/rest-api-spec/test/GeoExtension/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/opendatasoft/elasticsearch-plugin-geoshape/HEAD/src/test/resources/rest-api-spec/test/GeoExtension/.DS_Store -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /src/yamlRestTest/resources/rest-api-spec/test/GeoExtension/10_basic.yml: -------------------------------------------------------------------------------- 1 | "Geoshape plugin installed": 2 | - do: 3 | cluster.state: {} 4 | 5 | - set: {master_node: master} 6 | 7 | - do: 8 | nodes.info: {} 9 | 10 | - match: {nodes.$master.plugins.0.name: elasticsearch-plugin-geoshape} 11 | -------------------------------------------------------------------------------- /docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM docker.elastic.co/elasticsearch/elasticsearch:7.17.28 AS elasticsearch-plugin-debug 2 | 3 | COPY /build/distributions/elasticsearch-plugin-geoshape-7.17.28.0.zip /tmp/elasticsearch-plugin-geoshape-7.17.28.0.zip 4 | RUN ./bin/elasticsearch-plugin install file:/tmp/elasticsearch-plugin-geoshape-7.17.28.0.zip 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ### 7.17.28.0 2 | 3 | * Repackaging for Elasticsearch 7.17.28 4 | 5 | ### 7.17.6.1 6 | 7 | * Fix bbox on linestrings and points 8 | 9 | ### 7.17.6.0 10 | 11 | * Repackaging for ES 7.17.6 12 | 13 | ### 7.17.1.2 14 | 15 | * Simplify consistency: script is now using the same tolerance value as the agg one 16 | 17 | ### 7.17.1.1 18 | 19 | * Fix deduplication of points 20 | * Fix handling of GeometryCollections 21 | * Add tests 22 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | elasticsearch-plugin-debug: 3 | build: 4 | context: . 5 | dockerfile: docker/Dockerfile 6 | target: elasticsearch-plugin-debug 7 | environment: 8 | - discovery.type=single-node 9 | # NO DEBUG 10 | - ES_JAVA_OPTS=-Xms512m -Xmx512m 11 | # DEBUG 12 | # - ES_JAVA_OPTS=-Xms512m -Xmx512m -agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=*:5005 13 | ports: 14 | - "9200:9200" 15 | - "5005:5005" # DEBUG 16 | -------------------------------------------------------------------------------- /src/main/main.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.github/workflows/build.yaml: -------------------------------------------------------------------------------- 1 | name: compile-and-test 2 | 3 | on: 4 | pull_request: 5 | 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - name: Checkout sources 11 | uses: actions/checkout@v4 12 | - name: Setup Java 13 | uses: actions/setup-java@v4 14 | with: 15 | distribution: 'temurin' 16 | java-version: 21 17 | - name: Setup Gradle 18 | uses: gradle/actions/setup-gradle@v4 19 | - name: Check Format 20 | run: ./gradlew spotlessCheck 21 | - name: Compile 22 | run: ./gradlew assemble 23 | - name: Run Tests 24 | run: ./gradlew check 25 | -------------------------------------------------------------------------------- /src/main/java/org/opendatasoft/elasticsearch/search/aggregations/bucket/geoshape/GeoShape.java: -------------------------------------------------------------------------------- 1 | package org.opendatasoft.elasticsearch.search.aggregations.bucket.geoshape; 2 | 3 | import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * An aggregation of geo_shape using wkb field. 9 | */ 10 | public interface GeoShape extends MultiBucketsAggregation { 11 | interface Bucket extends MultiBucketsAggregation.Bucket {} 12 | 13 | enum Algorithm { 14 | DOUGLAS_PEUCKER, 15 | TOPOLOGY_PRESERVING 16 | } 17 | 18 | @Override 19 | List getBuckets(); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/yamlRestTest/java/org/opendatasoft/elasticsearch/RestApiYamlIT.java: -------------------------------------------------------------------------------- 1 | package org.opendatasoft.elasticsearch; 2 | 3 | import com.carrotsearch.randomizedtesting.annotations.Name; 4 | import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; 5 | 6 | import org.elasticsearch.test.rest.yaml.ClientYamlTestCandidate; 7 | import org.elasticsearch.test.rest.yaml.ESClientYamlSuiteTestCase; 8 | 9 | /* 10 | * Generic loader for yaml integration tests 11 | */ 12 | 13 | public class RestApiYamlIT extends ESClientYamlSuiteTestCase { 14 | public RestApiYamlIT(@Name("yaml") ClientYamlTestCandidate testCandidate) { 15 | super(testCandidate); 16 | } 17 | 18 | @ParametersFactory 19 | public static Iterable parameters() throws Exception { 20 | return ESClientYamlSuiteTestCase.createParameters(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/org/opendatasoft/elasticsearch/search/aggregations/bucket/geoshape/GeoShapeAggregatorSupplier.java: -------------------------------------------------------------------------------- 1 | package org.opendatasoft.elasticsearch.search.aggregations.bucket.geoshape; 2 | 3 | import org.elasticsearch.search.aggregations.Aggregator; 4 | import org.elasticsearch.search.aggregations.AggregatorFactories; 5 | import org.elasticsearch.search.aggregations.CardinalityUpperBound; 6 | import org.elasticsearch.search.aggregations.support.AggregationContext; 7 | import org.elasticsearch.search.aggregations.support.ValuesSource; 8 | import org.opendatasoft.elasticsearch.plugin.GeoUtils; 9 | 10 | import java.io.IOException; 11 | import java.util.Map; 12 | 13 | @FunctionalInterface 14 | public interface GeoShapeAggregatorSupplier { 15 | Aggregator build( 16 | String name, 17 | AggregatorFactories factories, 18 | AggregationContext context, 19 | ValuesSource valuesSource, 20 | GeoUtils.OutputFormat output_format, 21 | boolean must_simplify, 22 | int zoom, 23 | GeoShape.Algorithm algorithm, 24 | GeoShapeAggregator.BucketCountThresholds bucketCountThresholds, 25 | Aggregator parent, 26 | CardinalityUpperBound cardinalityUpperBound, 27 | Map metadata 28 | ) throws IOException; 29 | } 30 | -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | name: publish 2 | 3 | on: 4 | push: 5 | tags: ['v*'] 6 | release: 7 | types: [published] 8 | 9 | jobs: 10 | build-artifact: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v4 15 | 16 | - name: Tag Version Name Extraction 17 | id: version 18 | shell: bash 19 | run: | 20 | if [[ -n "${{ github.event.release.tag_name }}" ]]; then 21 | # Relase Github 22 | TAG_NAME="${{ github.event.release.tag_name }}" 23 | echo "📋 Triggered by GitHub release: $TAG_NAME" 24 | else 25 | # Just a new tag 26 | TAG_NAME=${GITHUB_REF#refs/tags/} 27 | echo "🏷️ Triggered by Git tag: $TAG_NAME" 28 | fi 29 | 30 | # Get rid of the 'v', e.g. v8.18.1.0 -> 8.18.1.0 31 | VERSION=${TAG_NAME#v} 32 | echo "version=$VERSION" >> $GITHUB_OUTPUT 33 | 34 | - name: Setup Java 35 | uses: actions/setup-java@v4 36 | with: 37 | distribution: 'temurin' 38 | java-version: 21 39 | 40 | - name: Setup Gradle 41 | uses: gradle/actions/setup-gradle@v4 42 | 43 | - name: Java Compilation 44 | run: ./gradlew -Pplugin_version=${{ steps.version.outputs.version }} clean assemble --no-daemon 45 | 46 | - name: Upload Plugin Artifact 47 | uses: actions/upload-artifact@v4 48 | with: 49 | name: elasticsearch-plugin-geoshape-${{ steps.version.outputs.version }} 50 | path: build/distributions/*.zip 51 | 52 | - name: Attach ZIP to GitHub Release 53 | uses: softprops/action-gh-release@v2 54 | if: github.event.release.tag_name != '' 55 | with: 56 | files: build/distributions/elasticsearch-plugin-geoshape-${{ steps.version.outputs.version }}.zip 57 | tag_name: ${{ github.event.release.tag_name }} 58 | env: 59 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 60 | -------------------------------------------------------------------------------- /src/main/java/org/opendatasoft/elasticsearch/plugin/GeoExtensionPlugin.java: -------------------------------------------------------------------------------- 1 | package org.opendatasoft.elasticsearch.plugin; 2 | 3 | import org.elasticsearch.common.settings.Settings; 4 | import org.elasticsearch.ingest.Processor; 5 | import org.elasticsearch.plugins.IngestPlugin; 6 | import org.elasticsearch.plugins.Plugin; 7 | import org.elasticsearch.plugins.ScriptPlugin; 8 | import org.elasticsearch.plugins.SearchPlugin; 9 | import org.elasticsearch.script.ScriptContext; 10 | import org.elasticsearch.script.ScriptEngine; 11 | import org.opendatasoft.elasticsearch.ingest.GeoExtensionProcessor; 12 | import org.opendatasoft.elasticsearch.script.ScriptGeoSimplify; 13 | import org.opendatasoft.elasticsearch.search.aggregations.bucket.geoshape.GeoShapeBuilder; 14 | import org.opendatasoft.elasticsearch.search.aggregations.bucket.geoshape.InternalGeoShape; 15 | 16 | import java.util.ArrayList; 17 | import java.util.Collection; 18 | import java.util.Collections; 19 | import java.util.Map; 20 | 21 | public class GeoExtensionPlugin extends Plugin implements IngestPlugin, ScriptPlugin, SearchPlugin { 22 | // Ingest plugin method 23 | @Override 24 | public Map getProcessors(Processor.Parameters parameters) { 25 | return Collections.singletonMap(GeoExtensionProcessor.TYPE, new GeoExtensionProcessor.Factory()); 26 | } 27 | 28 | // Script plugin method 29 | @Override 30 | public ScriptEngine getScriptEngine(Settings settings, Collection> contexts) { 31 | return new ScriptGeoSimplify(); 32 | } 33 | 34 | // Search plugin method 35 | @Override 36 | public ArrayList getAggregations() { 37 | ArrayList r = new ArrayList<>(); 38 | 39 | r.add( 40 | new SearchPlugin.AggregationSpec(GeoShapeBuilder.NAME, GeoShapeBuilder::new, GeoShapeBuilder::parse).addResultReader( 41 | InternalGeoShape::new 42 | ).setAggregatorRegistrar(GeoShapeBuilder::registerAggregators) 43 | ); 44 | 45 | return r; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /src/yamlRestTest/resources/rest-api-spec/test/GeoExtension/50_invalid_polygon.yml: -------------------------------------------------------------------------------- 1 | --- 2 | "Test aggregation": 3 | 4 | # Create the pipeline, index and mapping 5 | - do: 6 | ingest.put_pipeline: 7 | id: "geo_extension" 8 | body: > 9 | { 10 | "description": "Add extra geo fields to geo_shape fields.", 11 | "processors": [ 12 | { 13 | "geo_extension": { 14 | "field": "geo_shape_*" 15 | } 16 | } 17 | ] 18 | } 19 | - match: { acknowledged: true } 20 | 21 | - do: 22 | ingest.get_pipeline: 23 | id: "geo_extension" 24 | - match: { geo_extension.description: "Add extra geo fields to geo_shape fields." } 25 | 26 | - do: 27 | indices.create: 28 | index: test_index 29 | 30 | - do: 31 | indices.put_mapping: 32 | index: test_index 33 | body: 34 | dynamic_templates: [ 35 | { 36 | "geo_shapes": { 37 | "match": "geo_shape_*", 38 | "mapping": { 39 | "properties": { 40 | "shape": {"enabled": false}, 41 | "fixed_shape": {"type": "geo_shape"}, 42 | "hash": {"type": "keyword"}, 43 | "wkb": {"type": "binary", "doc_values": true}, 44 | "type": {"type": "keyword"}, 45 | "area": {"type": "half_float"}, 46 | "bbox": {"type": "geo_point"}, 47 | "centroid": {"type": "geo_point"} 48 | } 49 | } 50 | } 51 | } 52 | ] 53 | 54 | # Add documents 55 | # An invalid Polygon for Elastic 7.17.6 and Lucene 8.11.3 BUT valid for Lucene 8.11.3 56 | - do: 57 | index: 58 | index: test_index 59 | pipeline: "geo_extension" 60 | body: { 61 | "id": 1, 62 | "name": "invalid", 63 | "geo_shape_0": "POLYGON ((-88.3245325358123 41.9306419084828,-88.3243288475156 41.9308130944597,-88.3244513948451 41.930891654082,-88.3246174067624 41.930998076295,-88.3245448815692 41.9310557712027,-88.3239353718069 41.9313272600886,-88.3237355617867 41.9313362704162,-88.3237347670323 41.9311150951881,-88.3237340649402 41.931103661118,-88.3235660813522 41.9311112432041,-88.3234509652339 41.9311164377155,-88.3232353124097 41.9311261692953,-88.3232343331295 41.9313588701899,-88.323028772523 41.9313681383084,-88.3229999744274 41.930651995613,-88.3236147717043 41.9303655647412,-88.323780013667 41.929458561339,-88.3240657895016 41.9293998882959,-88.3243948640426 41.9293028003164,-88.324740490767 41.9301340399879,-88.3251305560187 41.9302766363048,-88.3248260581475 41.9308286995884,-88.3246595186817 41.9307227160738,-88.3245325358123 41.9306419084828),(-88.3245658060855 41.930351580587,-88.3246004191532 41.9302095159456,-88.3246375011905 41.9300573183932,-88.3243392233337 41.9300159738164,-88.3243011787553 41.9301696594472,-88.3242661951392 41.9303109843373,-88.3245658060855 41.930351580587),(-88.3245325358123 41.9306419084828,-88.3245478066552 41.9305086556331,-88.3245658060855 41.930351580587,-88.3242368660096 41.9303327977821,-88.3242200926128 41.9304905242189,-88.324206161464 41.9306215207536,-88.3245325358123 41.9306419084828),(-88.3236767661893 41.9307089429871,-88.3237008716322 41.930748885445,-88.323876104365 41.9306891087739,-88.324063438129 41.9306252050871,-88.3239244290607 41.930399373909,-88.3237349076233 41.9304653056436,-88.3235653339759 41.9305242981369,-88.3236767661893 41.9307089429871))" 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/org/opendatasoft/elasticsearch/search/aggregations/bucket/geoshape/GeoShapeAggregatorFactory.java: -------------------------------------------------------------------------------- 1 | package org.opendatasoft.elasticsearch.search.aggregations.bucket.geoshape; 2 | 3 | import org.elasticsearch.search.aggregations.Aggregator; 4 | import org.elasticsearch.search.aggregations.AggregatorFactories; 5 | import org.elasticsearch.search.aggregations.AggregatorFactory; 6 | import org.elasticsearch.search.aggregations.CardinalityUpperBound; 7 | import org.elasticsearch.search.aggregations.InternalAggregation; 8 | import org.elasticsearch.search.aggregations.NonCollectingAggregator; 9 | import org.elasticsearch.search.aggregations.support.AggregationContext; 10 | import org.elasticsearch.search.aggregations.support.ValuesSource; 11 | import org.elasticsearch.search.aggregations.support.ValuesSourceAggregatorFactory; 12 | import org.elasticsearch.search.aggregations.support.ValuesSourceConfig; 13 | import org.opendatasoft.elasticsearch.plugin.GeoUtils; 14 | 15 | import java.io.IOException; 16 | import java.util.ArrayList; 17 | import java.util.Map; 18 | 19 | class GeoShapeAggregatorFactory extends ValuesSourceAggregatorFactory { 20 | 21 | private GeoUtils.OutputFormat output_format; 22 | private boolean must_simplify; 23 | private int zoom; 24 | private GeoShape.Algorithm algorithm; 25 | private final GeoShapeAggregator.BucketCountThresholds bucketCountThresholds; 26 | 27 | GeoShapeAggregatorFactory( 28 | String name, 29 | ValuesSourceConfig config, 30 | GeoUtils.OutputFormat output_format, 31 | boolean must_simplify, 32 | int zoom, 33 | GeoShape.Algorithm algorithm, 34 | GeoShapeAggregator.BucketCountThresholds bucketCountThresholds, 35 | AggregationContext context, 36 | AggregatorFactory parent, 37 | AggregatorFactories.Builder subFactoriesBuilder, 38 | Map metaData 39 | ) throws IOException { 40 | super(name, config, context, parent, subFactoriesBuilder, metaData); 41 | this.output_format = output_format; 42 | this.must_simplify = must_simplify; 43 | this.zoom = zoom; 44 | this.algorithm = algorithm; 45 | this.bucketCountThresholds = bucketCountThresholds; 46 | } 47 | 48 | @Override 49 | protected Aggregator createUnmapped(Aggregator parent, Map metadata) throws IOException { 50 | final InternalAggregation aggregation = new InternalGeoShape( 51 | name, 52 | new ArrayList<>(), 53 | output_format, 54 | bucketCountThresholds.getRequiredSize(), 55 | bucketCountThresholds.getShardSize(), 56 | metadata 57 | ); 58 | return new NonCollectingAggregator(name, context, parent, factories, metadata) { 59 | @Override 60 | public InternalAggregation buildEmptyAggregation() { 61 | return aggregation; 62 | } 63 | }; 64 | } 65 | 66 | @Override 67 | protected Aggregator doCreateInternal(Aggregator parent, CardinalityUpperBound cardinality, Map metadata) 68 | throws IOException { 69 | GeoShapeAggregator.BucketCountThresholds bucketCountThresholds = new GeoShapeAggregator.BucketCountThresholds( 70 | this.bucketCountThresholds 71 | ); 72 | bucketCountThresholds.ensureValidity(); 73 | ValuesSource valuesSourceBytes = config.getValuesSource(); 74 | return new GeoShapeAggregator( 75 | name, 76 | factories, 77 | context, 78 | valuesSourceBytes, 79 | output_format, 80 | must_simplify, 81 | zoom, 82 | algorithm, 83 | bucketCountThresholds, 84 | parent, 85 | cardinality, 86 | metadata 87 | ); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/test/java/org/opendatasoft/elasticsearch/plugin/GeoUtilsTests.java: -------------------------------------------------------------------------------- 1 | package org.opendatasoft.elasticsearch.plugin; 2 | 3 | import org.elasticsearch.geometry.Line; 4 | import org.elasticsearch.geometry.LinearRing; 5 | import org.elasticsearch.geometry.MultiPolygon; 6 | import org.elasticsearch.geometry.Polygon; 7 | import org.elasticsearch.test.ESTestCase; 8 | import org.locationtech.jts.geom.Coordinate; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | /** 14 | * Simple tests for some GeoUtils functions such as coordinates deduplication for different Geom shape. 15 | */ 16 | public class GeoUtilsTests extends ESTestCase { 17 | 18 | public void testBasicConfiguration() { 19 | assertTrue("Configuration OK", true); 20 | assertEquals("Dumb basic assertion", 1, 1); 21 | } 22 | 23 | public void testRemoveConsecutiveDuplicateCoordinatesFromLine() { 24 | // The third point is duplicated. 25 | double[] coordX = { 0.0, 1.0, 1.0, 1.0, 0.0 }; 26 | double[] coordY = { 0.0, 0.0, 0.0, 1.0, 1.0 }; 27 | Line original = new Line(coordX, coordY); 28 | Line result = GeoUtils.removeDuplicateCoordinates(original); 29 | assertEquals("Should find 4 coordinates instead of 5", 4, result.length()); 30 | } 31 | 32 | public void testRemoveConsecutiveDuplicateCoordinatesFromPolygon() { 33 | List coordinates = createRectangleCoordinatesWithDuplicates(3, 3, 5, 5); 34 | LinearRing ring = createLinearRingFromCoordinates(coordinates); 35 | Polygon original = new Polygon(ring); 36 | Polygon result = GeoUtils.removeDuplicateCoordinates(original); 37 | assertEquals("Should find 5 coordinates instead of 7", 5, result.getPolygon().length()); 38 | } 39 | 40 | public void testRemoveConsecutiveDuplicateCoordinatesFromRealWorldPolygon() { 41 | List coordinates = new ArrayList<>(); 42 | coordinates.add(new Coordinate(2.3522219, 48.856614)); // Paris 43 | coordinates.add(new Coordinate(2.3522219, 48.856614)); // duplicate 44 | coordinates.add(new Coordinate(2.3541049, 48.856614001)); // very close 45 | coordinates.add(new Coordinate(2.3541049, 48.856614001)); // duplicate exact 46 | coordinates.add(new Coordinate(2.3541049, 48.8586972)); 47 | coordinates.add(new Coordinate(2.3522219, 48.8586972)); 48 | coordinates.add(new Coordinate(2.3522219, 48.856614)); // close 49 | coordinates.add(new Coordinate(2.3522219, 48.856614)); // duplicate 50 | LinearRing ring = createLinearRingFromCoordinates(coordinates); 51 | Polygon original = new Polygon(ring); 52 | Polygon result = GeoUtils.removeDuplicateCoordinates(original); 53 | assertTrue("Should find less that 6", result.getPolygon().length() < 6); 54 | } 55 | 56 | public void testRemoveDuplicatesInHoles() { 57 | // A Polygon with a hole. The hole can have some duplicates. 58 | List rectCoordinates = new ArrayList<>(); 59 | rectCoordinates.add(new Coordinate(-2.0, -2.0)); 60 | rectCoordinates.add(new Coordinate(2.0, -2.0)); 61 | rectCoordinates.add(new Coordinate(2.0, -2.0)); // duplicate 62 | rectCoordinates.add(new Coordinate(2.0, 2.0)); 63 | rectCoordinates.add(new Coordinate(-2.0, 2.0)); 64 | rectCoordinates.add(new Coordinate(-2.0, -2.0)); 65 | LinearRing ring = createLinearRingFromCoordinates(rectCoordinates); 66 | 67 | List holeCoordinates = new ArrayList<>(); 68 | holeCoordinates.add(new Coordinate(-1, 0)); 69 | holeCoordinates.add(new Coordinate(1, 0)); 70 | holeCoordinates.add(new Coordinate(1, 0)); // duplicate 71 | holeCoordinates.add(new Coordinate(0, 0)); 72 | holeCoordinates.add(new Coordinate(0, 0)); // duplicate 73 | holeCoordinates.add(new Coordinate(-1.0, 0)); // close 74 | holeCoordinates.add(new Coordinate(-1.0, 0)); // duplicate 75 | List holes = new ArrayList<>(); 76 | LinearRing hole = createLinearRingFromCoordinates(holeCoordinates); 77 | holes.add(hole); 78 | 79 | // A polygon with a single hole. 80 | Polygon original = new Polygon(ring, holes); 81 | Polygon result = GeoUtils.removeDuplicateCoordinates(original); 82 | assertEquals("There should be one hole", 1, result.getNumberOfHoles()); 83 | assertEquals("Should find 4 coordinates in the hole instead of 6", 4, result.getHole(0).length()); 84 | assertEquals("Should find 5 coordinates instead of 6", 5, result.getPolygon().length()); 85 | } 86 | 87 | public void testRemoveDuplicateCoordForMultiPolygon() { 88 | List polygons = new ArrayList<>(); 89 | 90 | // First polygon with some duplicated coordinates 91 | List poly1Coords = createRectangleCoordinatesWithDuplicates(0, 0, 2, 2); 92 | polygons.add(new Polygon(createLinearRingFromCoordinates(poly1Coords))); 93 | 94 | // Second polygon with some duplicated coordinates 95 | List poly2Coords = createRectangleCoordinatesWithDuplicates(5, 5, 7, 7); 96 | polygons.add(new Polygon(createLinearRingFromCoordinates(poly2Coords))); 97 | 98 | MultiPolygon original = new MultiPolygon(polygons); 99 | MultiPolygon result = GeoUtils.removeDuplicateCoordinates(original); 100 | 101 | assertEquals("Original polygon should have 2 polygons", 2, original.size()); 102 | assertEquals("Should have 2 polygons", 2, result.size()); 103 | 104 | // Check each polygon 105 | for (int i = 0; i < result.size(); i++) { 106 | Polygon polygon = result.get(i); 107 | LinearRing exteriorRing = polygon.getPolygon(); 108 | assertEquals("Each polygon should have 5 points", 5, exteriorRing.length()); 109 | assertValidClosedRing(exteriorRing); 110 | } 111 | } 112 | 113 | private void assertValidClosedRing(LinearRing ring) { 114 | assertTrue("The ring should have at least 4 points", ring.length() >= 4); 115 | 116 | double[] lats = ring.getLats(); 117 | double[] lons = ring.getLons(); 118 | 119 | assertEquals("The ring should be closed (latitude)", lats[0], lats[lats.length - 1], 1e-10); 120 | assertEquals("The ring should closed (longitude)", lons[0], lons[lons.length - 1], 1e-10); 121 | } 122 | 123 | private List createRectangleCoordinatesWithDuplicates(double minX, double minY, double maxX, double maxY) { 124 | List coords = new ArrayList<>(); 125 | coords.add(new Coordinate(minX, minY)); 126 | coords.add(new Coordinate(minX, minY)); // duplicate 127 | coords.add(new Coordinate(maxX, minY)); 128 | coords.add(new Coordinate(maxX, maxY)); 129 | coords.add(new Coordinate(maxX, maxY)); // duplicate 130 | coords.add(new Coordinate(minX, maxY)); 131 | coords.add(new Coordinate(minX, minY)); // fermeture 132 | return coords; 133 | } 134 | 135 | private LinearRing createLinearRingFromCoordinates(List coordinates) { 136 | // Extract the x values (longitudes) and y values (latitudes) with streams 137 | double[] lons = coordinates.stream().mapToDouble(coord -> coord.x).toArray(); 138 | double[] lats = coordinates.stream().mapToDouble(coord -> coord.y).toArray(); 139 | 140 | return new LinearRing(lats, lons); 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /src/main/java/org/opendatasoft/elasticsearch/script/ScriptGeoSimplify.java: -------------------------------------------------------------------------------- 1 | package org.opendatasoft.elasticsearch.script; 2 | 3 | import org.apache.lucene.index.LeafReaderContext; 4 | import org.apache.lucene.util.BytesRef; 5 | import org.elasticsearch.index.fielddata.ScriptDocValues; 6 | import org.elasticsearch.script.FieldScript; 7 | import org.elasticsearch.script.ScriptContext; 8 | import org.elasticsearch.script.ScriptEngine; 9 | import org.elasticsearch.script.ScriptException; 10 | import org.elasticsearch.search.lookup.SearchLookup; 11 | import org.locationtech.jts.geom.Geometry; 12 | import org.locationtech.jts.geom.GeometryFactory; 13 | import org.locationtech.jts.io.ParseException; 14 | import org.locationtech.jts.io.WKBReader; 15 | import org.locationtech.jts.io.geojson.GeoJsonWriter; 16 | import org.locationtech.jts.simplify.DouglasPeuckerSimplifier; 17 | import org.locationtech.jts.simplify.TopologyPreservingSimplifier; 18 | import org.opendatasoft.elasticsearch.plugin.GeoUtils; 19 | 20 | import java.util.Collections; 21 | import java.util.HashMap; 22 | import java.util.Locale; 23 | import java.util.Map; 24 | import java.util.Set; 25 | 26 | public class ScriptGeoSimplify implements ScriptEngine { 27 | public static final ScriptContext CONTEXT = new ScriptContext<>("geo_simplify", GeoSearchLeafFactory.class); 28 | 29 | @Override 30 | public String getType() { 31 | return "geo_extension_scripts"; 32 | } 33 | 34 | @Override 35 | public T compile(String scriptName, String scriptSource, ScriptContext context, Map params) { 36 | if (!context.equals(FieldScript.CONTEXT)) { 37 | throw new IllegalArgumentException(getType() + " scripts cannot be used for context [" + context.name + "]"); 38 | } 39 | if ("geo_simplify".equals(scriptName)) { 40 | FieldScript.Factory factory = GeoSearchLeafFactory::new; 41 | return context.factoryClazz.cast(factory); 42 | } 43 | throw new IllegalArgumentException("Unknown script name " + scriptSource); 44 | } 45 | 46 | @Override 47 | public Set> getSupportedContexts() { 48 | return Collections.singleton(CONTEXT); 49 | } 50 | 51 | @Override 52 | public void close() { 53 | // optionally close resources 54 | } 55 | 56 | private static class GeoSearchLeafFactory implements FieldScript.LeafFactory { 57 | private final Map params; 58 | private final SearchLookup lookup; 59 | private final String field; 60 | private final int zoom; 61 | GeoUtils.OutputFormat output_format; 62 | GeoUtils.SimplifyAlgorithm algorithm; 63 | // private final int geojson_decimals; 64 | GeoJsonWriter geoJsonWriter; 65 | 66 | private Geometry getSimplifiedShape(Geometry geometry) { 67 | double lat = geometry.getCentroid().getCoordinate().y; 68 | double meterByPixel = GeoUtils.getMeterByPixel(zoom, lat); 69 | 70 | // double tolerance = 360 / (256 * Math.pow(zoom, 3)); 71 | double tolerance = GeoUtils.getDecimalDegreeFromMeter(meterByPixel, lat); 72 | if (algorithm == GeoUtils.SimplifyAlgorithm.TOPOLOGY_PRESERVING) return TopologyPreservingSimplifier.simplify( 73 | geometry, 74 | tolerance 75 | ); 76 | else return DouglasPeuckerSimplifier.simplify(geometry, tolerance); 77 | } 78 | 79 | private GeoSearchLeafFactory(Map params, SearchLookup lookup) { 80 | 81 | if (params.isEmpty()) { 82 | throw new IllegalArgumentException("[params] field is mandatory"); 83 | 84 | } 85 | if (!params.containsKey("field")) { 86 | throw new IllegalArgumentException("Missing mandatory parameter [field]"); 87 | } 88 | if (!params.containsKey("zoom")) { 89 | throw new IllegalArgumentException("Missing mandatory parameter [zoom]"); 90 | } 91 | this.params = params; 92 | this.lookup = lookup; 93 | field = params.get("field").toString(); 94 | zoom = (int) params.get("zoom"); 95 | 96 | output_format = GeoUtils.OutputFormat.GEOJSON; 97 | if (params.containsKey("output_format")) { 98 | String string_output_format = params.get("output_format").toString(); 99 | if (string_output_format != null) output_format = GeoUtils.OutputFormat.valueOf( 100 | string_output_format.toUpperCase(Locale.getDefault()) 101 | ); 102 | } 103 | 104 | algorithm = GeoUtils.SimplifyAlgorithm.DOUGLAS_PEUCKER; 105 | if (params.containsKey("algorithm")) { 106 | String algorithm_string = params.get("algorithm").toString(); 107 | if (algorithm_string != null) algorithm = GeoUtils.SimplifyAlgorithm.valueOf( 108 | algorithm_string.toUpperCase(Locale.getDefault()) 109 | ); 110 | } 111 | 112 | // geojson_decimals = 20; 113 | geoJsonWriter = new GeoJsonWriter(); 114 | } 115 | 116 | @Override 117 | public FieldScript newInstance(LeafReaderContext context) { 118 | return new FieldScript(params, lookup, context) { 119 | @Override 120 | public Object execute() { 121 | Map resMap = new HashMap<>(); 122 | 123 | BytesRef wkb; 124 | try { 125 | ScriptDocValues values_list = getDoc().get(field); 126 | wkb = (BytesRef) values_list.get(0); 127 | } catch (Exception e) { 128 | return resMap; 129 | } 130 | 131 | GeometryFactory geometryFactory = new GeometryFactory(); 132 | try { 133 | Geometry geom = new WKBReader().read(wkb.bytes); 134 | String realType = geom.getGeometryType(); 135 | Geometry simplifiedGeom = getSimplifiedShape(geom); 136 | if (!simplifiedGeom.isEmpty()) { 137 | resMap.put("shape", GeoUtils.exportGeoTo(simplifiedGeom, output_format, geoJsonWriter)); 138 | resMap.put("type", simplifiedGeom.getGeometryType()); 139 | resMap.put("real_type", realType); 140 | } else { 141 | // If the simplified polygon is empty because it was too small, return a point 142 | resMap.put( 143 | "shape", 144 | GeoUtils.exportGeoTo(geometryFactory.createPoint(geom.getCoordinate()), output_format, geoJsonWriter) 145 | ); 146 | resMap.put("type", "SimplificationPoint"); 147 | } 148 | } catch (ParseException e) { 149 | throw new ScriptException( 150 | "Can't parse WKB", 151 | e.getCause(), 152 | Collections.emptyList(), 153 | "geo_simplified", 154 | "geo_extension_scripts" 155 | ); 156 | } 157 | 158 | return resMap; 159 | } 160 | 161 | }; 162 | } 163 | 164 | } 165 | 166 | } 167 | -------------------------------------------------------------------------------- /src/yamlRestTest/resources/rest-api-spec/test/GeoExtension/40_geoshape_aggregation.yml: -------------------------------------------------------------------------------- 1 | --- 2 | "Test aggregation": 3 | 4 | # Create the pipeline, index and mapping 5 | - do: 6 | ingest.put_pipeline: 7 | id: "geo_extension" 8 | body: > 9 | { 10 | "description": "Add extra geo fields to geo_shape fields.", 11 | "processors": [ 12 | { 13 | "geo_extension": { 14 | "field": "geo_shape_*" 15 | } 16 | } 17 | ] 18 | } 19 | - match: { acknowledged: true } 20 | 21 | - do: 22 | ingest.get_pipeline: 23 | id: "geo_extension" 24 | - match: { geo_extension.description: "Add extra geo fields to geo_shape fields." } 25 | 26 | - do: 27 | indices.create: 28 | index: test_index 29 | 30 | - do: 31 | indices.put_mapping: 32 | index: test_index 33 | body: 34 | dynamic_templates: [ 35 | { 36 | "geo_shapes": { 37 | "match": "geo_shape_*", 38 | "mapping": { 39 | "properties": { 40 | "shape": {"enabled": false}, 41 | "fixed_shape": {"type": "geo_shape"}, 42 | "hash": {"type": "keyword"}, 43 | "wkb": {"type": "binary", "doc_values": true}, 44 | "type": {"type": "keyword"}, 45 | "area": {"type": "half_float"}, 46 | "bbox": {"type": "geo_point"}, 47 | "centroid": {"type": "geo_point"} 48 | } 49 | } 50 | } 51 | } 52 | ] 53 | 54 | # Add documents 55 | - do: 56 | index: 57 | index: test_index 58 | pipeline: "geo_extension" 59 | body: { 60 | "id": 1, 61 | "geo_shape_0": { 62 | "type": "Polygon", 63 | "coordinates": [ 64 | [ 65 | [ 66 | -3.3858489990234375, 67 | 47.7442871774986 68 | ], 69 | [ 70 | -3.3889389038085938, 71 | 47.73770713305151 72 | ], 73 | [ 74 | -3.3777809143066406, 75 | 47.738515253481545 76 | ], 77 | [ 78 | -3.3858489990234375, 79 | 47.7442871774986 80 | ] 81 | ] 82 | ] 83 | } 84 | } 85 | 86 | - do: 87 | index: 88 | index: test_index 89 | pipeline: "geo_extension" 90 | body: { 91 | "id": 2, 92 | "geo_shape_0": { 93 | "type": "LineString", 94 | "coordinates": [ 95 | [ 96 | -3.3805704116821285, 97 | 47.75757459952785 98 | ], 99 | [ 100 | -3.3811068534851074, 101 | 47.757711639949754 102 | ], 103 | [ 104 | -3.3817613124847408, 105 | 47.75771524627175 106 | ], 107 | [ 108 | -3.3826088905334473, 109 | 47.75768278936459 110 | ], 111 | [ 112 | -3.3831185102462764, 113 | 47.75758181219062 114 | ] 115 | ] 116 | } 117 | } 118 | 119 | - do: 120 | index: 121 | index: test_index 122 | pipeline: "geo_extension" 123 | body: { 124 | "id": 3, 125 | "name": "Le BHV Marais - Paris", 126 | "geo_shape_0": {"type": "Polygon", "coordinates": [[[2.3525621, 48.857395999727686], [2.3525681, 48.85737839972767], [2.3525818, 48.8573607997277], [2.3526161, 48.85734039972769], [2.3526682, 48.857330099727704], [2.3527051, 48.85733319972769], [2.3527095, 48.85732729972771], [2.3527088, 48.85732179972772], [2.3527346, 48.8573134997277], [2.3528807, 48.85728029972772], [2.3530401, 48.857241799727724], [2.3531794, 48.85720819972773], [2.3532811, 48.85718359972775], [2.3534759, 48.85713659972777], [2.3536211, 48.857101599727756], [2.3537783, 48.85706359972777], [2.3538754, 48.85709369972776], [2.3538906, 48.85712099972776], [2.3539385, 48.857206799727734], [2.3540005, 48.857317999727705], [2.3540525, 48.857411199727686], [2.3540721, 48.857446399727685], [2.3540668, 48.85744779972767], [2.3540707, 48.857472599727664], [2.3540622, 48.857497599727665], [2.3540541, 48.857508299727655], [2.3540239, 48.857528399727634], [2.3540001, 48.85753509972766], [2.3540023, 48.85753889972765], [2.3539471, 48.857558899727636], [2.3538824, 48.85758219972763], [2.3538218, 48.85760409972764], [2.3537725, 48.85762189972764], [2.3537123, 48.85764369972763], [2.3536506, 48.85766599972763], [2.3536151, 48.85767879972762], [2.3535832, 48.85769029972763], [2.3535222, 48.8577123997276], [2.3534533, 48.8577372997276], [2.3533762, 48.85776509972759], [2.3532997, 48.8577927997276], [2.353232, 48.85781719972759], [2.3531528, 48.857845799727585], [2.3531009, 48.85786459972756], [2.3530659, 48.857872399727576], [2.3530474, 48.85787309972757], [2.3530175, 48.85787069972757], [2.3529784, 48.857856999727574], [2.3529624, 48.85784619972758], [2.3529494, 48.857833299727574], [2.3529439, 48.857834699727576], [2.3529125, 48.857800499727595], [2.3528479, 48.8577299997276], [2.3527546, 48.85762839972763], [2.3526549, 48.857519699727646], [2.3526422, 48.85750589972766], [2.3526216, 48.85748359972768], [2.3526279, 48.85747989972768], [2.352624, 48.857477099727674], [2.3526301, 48.85747449972769], [2.3526191, 48.85746599972768], [2.3525904, 48.857452299727655], [2.3525766, 48.85744089972767], [2.352564, 48.85741979972767], [2.3525621, 48.857395999727686]]]} 127 | } 128 | 129 | - do: 130 | indices.refresh: {} 131 | 132 | # Test polygon simplification with douglas peucker 133 | # With zoom=1, polygon is reduced to a point 134 | - do: 135 | search: 136 | body: 137 | query: 138 | term: 139 | id: 1 140 | size: 0 141 | aggs: 142 | g: 143 | geoshape: 144 | field: "geo_shape_0.wkb" 145 | output_format: geojson 146 | simplify: 147 | zoom: 1 148 | algorithm: DOUGLAS_PEUCKER 149 | size: 4 150 | 151 | - match: {aggregations.g.buckets.0.key: "{\"type\":\"Point\",\"coordinates\":[-3.3889389,47.73770713],\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:0\"}}}" } 152 | 153 | # With topology preservation 154 | - do: 155 | search: 156 | body: 157 | query: 158 | term: 159 | id: 1 160 | size: 0 161 | aggs: 162 | g: 163 | geoshape: 164 | field: "geo_shape_0.wkb" 165 | output_format: geojson 166 | simplify: 167 | zoom: 1 168 | algorithm: TOPOLOGY_PRESERVING 169 | size: 4 170 | 171 | - match: {aggregations.g.buckets.0.key: "{\"type\":\"Polygon\",\"coordinates\":[[[-3.3889389,47.73770713],[-3.37778091,47.73851525],[-3.385849,47.74428718],[-3.3889389,47.73770713]]],\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:0\"}}}"} 172 | 173 | # Test size restriction will return the largest shape 174 | - do: 175 | search: 176 | body: 177 | size: 0 178 | aggs: 179 | g: 180 | geoshape: 181 | field: "geo_shape_0.wkb" 182 | output_format: geojson 183 | simplify: 184 | zoom: 1 185 | algorithm: TOPOLOGY_PRESERVING 186 | size: 1 # size restriction here 187 | 188 | - match: {aggregations.g.buckets.0.key: "{\"type\":\"Polygon\",\"coordinates\":[[[-3.3889389,47.73770713],[-3.37778091,47.73851525],[-3.385849,47.74428718],[-3.3889389,47.73770713]]],\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:0\"}}}"} 189 | 190 | # test with high zoom and TOPOLOGY_PRESERVING (exact same test as 30_simplify_script.yml one!) 191 | - do: 192 | search: 193 | body: 194 | size: 0 195 | aggs: 196 | g: 197 | geoshape: 198 | field: "geo_shape_0.wkb" 199 | output_format: geojson 200 | simplify: 201 | zoom: 20 202 | algorithm: TOPOLOGY_PRESERVING 203 | 204 | # coordinates length must be 37. it's not possible to test this length because the shape is dumped as a text, so we're testing the full shape length here instead 205 | - length: {aggregations.g.buckets.1.key: 935} 206 | -------------------------------------------------------------------------------- /src/yamlRestTest/resources/rest-api-spec/test/GeoExtension/30_simplify_script.yml: -------------------------------------------------------------------------------- 1 | --- 2 | "Test simplification script": 3 | 4 | # Create the pipeline, index and mapping 5 | - do: 6 | ingest.put_pipeline: 7 | id: "geo_extension" 8 | body: > 9 | { 10 | "description": "Add extra geo fields to geo_shape fields.", 11 | "processors": [ 12 | { 13 | "geo_extension": { 14 | "field": "geo_shape_*" 15 | } 16 | } 17 | ] 18 | } 19 | - match: { acknowledged: true } 20 | 21 | - do: 22 | ingest.get_pipeline: 23 | id: "geo_extension" 24 | - match: { geo_extension.description: "Add extra geo fields to geo_shape fields." } 25 | 26 | - do: 27 | indices.create: 28 | index: test_index 29 | 30 | - do: 31 | indices.put_mapping: 32 | index: test_index 33 | body: 34 | dynamic_templates: [ 35 | { 36 | "geo_shapes": { 37 | "match": "geo_shape_*", 38 | "mapping": { 39 | "properties": { 40 | "shape": {"enabled": false}, 41 | "fixed_shape": {"type": "geo_shape"}, 42 | "hash": {"type": "keyword"}, 43 | "wkb": {"type": "binary", "doc_values": true}, 44 | "type": {"type": "keyword"}, 45 | "area": {"type": "half_float"}, 46 | "bbox": {"type": "geo_point"}, 47 | "centroid": {"type": "geo_point"} 48 | } 49 | } 50 | } 51 | } 52 | ] 53 | 54 | # Add documents 55 | - do: 56 | index: 57 | index: test_index 58 | pipeline: "geo_extension" 59 | body: { 60 | "id": 1, 61 | "geo_shape_0": { 62 | "type": "Polygon", 63 | "coordinates": [ 64 | [ 65 | [ 66 | -3.3858489990234375, 67 | 47.7442871774986 68 | ], 69 | [ 70 | -3.3889389038085938, 71 | 47.73770713305151 72 | ], 73 | [ 74 | -3.3777809143066406, 75 | 47.738515253481545 76 | ], 77 | [ 78 | -3.3858489990234375, 79 | 47.7442871774986 80 | ] 81 | ] 82 | ] 83 | } 84 | } 85 | 86 | - do: 87 | index: 88 | index: test_index 89 | pipeline: "geo_extension" 90 | body: { 91 | "id": 2, 92 | "geo_shape_0": { 93 | "type": "LineString", 94 | "coordinates": [ 95 | [ 96 | -3.3805704116821285, 97 | 47.75757459952785 98 | ], 99 | [ 100 | -3.3811068534851074, 101 | 47.757711639949754 102 | ], 103 | [ 104 | -3.3817613124847408, 105 | 47.75771524627175 106 | ], 107 | [ 108 | -3.3826088905334473, 109 | 47.75768278936459 110 | ], 111 | [ 112 | -3.3831185102462764, 113 | 47.75758181219062 114 | ] 115 | ] 116 | } 117 | } 118 | 119 | - do: 120 | index: 121 | index: test_index 122 | pipeline: "geo_extension" 123 | body: { 124 | "id": 3, 125 | "name": "Le BHV Marais - Paris", 126 | "geo_shape_0": {"type": "Polygon", "coordinates": [[[2.3525621, 48.857395999727686], [2.3525681, 48.85737839972767], [2.3525818, 48.8573607997277], [2.3526161, 48.85734039972769], [2.3526682, 48.857330099727704], [2.3527051, 48.85733319972769], [2.3527095, 48.85732729972771], [2.3527088, 48.85732179972772], [2.3527346, 48.8573134997277], [2.3528807, 48.85728029972772], [2.3530401, 48.857241799727724], [2.3531794, 48.85720819972773], [2.3532811, 48.85718359972775], [2.3534759, 48.85713659972777], [2.3536211, 48.857101599727756], [2.3537783, 48.85706359972777], [2.3538754, 48.85709369972776], [2.3538906, 48.85712099972776], [2.3539385, 48.857206799727734], [2.3540005, 48.857317999727705], [2.3540525, 48.857411199727686], [2.3540721, 48.857446399727685], [2.3540668, 48.85744779972767], [2.3540707, 48.857472599727664], [2.3540622, 48.857497599727665], [2.3540541, 48.857508299727655], [2.3540239, 48.857528399727634], [2.3540001, 48.85753509972766], [2.3540023, 48.85753889972765], [2.3539471, 48.857558899727636], [2.3538824, 48.85758219972763], [2.3538218, 48.85760409972764], [2.3537725, 48.85762189972764], [2.3537123, 48.85764369972763], [2.3536506, 48.85766599972763], [2.3536151, 48.85767879972762], [2.3535832, 48.85769029972763], [2.3535222, 48.8577123997276], [2.3534533, 48.8577372997276], [2.3533762, 48.85776509972759], [2.3532997, 48.8577927997276], [2.353232, 48.85781719972759], [2.3531528, 48.857845799727585], [2.3531009, 48.85786459972756], [2.3530659, 48.857872399727576], [2.3530474, 48.85787309972757], [2.3530175, 48.85787069972757], [2.3529784, 48.857856999727574], [2.3529624, 48.85784619972758], [2.3529494, 48.857833299727574], [2.3529439, 48.857834699727576], [2.3529125, 48.857800499727595], [2.3528479, 48.8577299997276], [2.3527546, 48.85762839972763], [2.3526549, 48.857519699727646], [2.3526422, 48.85750589972766], [2.3526216, 48.85748359972768], [2.3526279, 48.85747989972768], [2.352624, 48.857477099727674], [2.3526301, 48.85747449972769], [2.3526191, 48.85746599972768], [2.3525904, 48.857452299727655], [2.3525766, 48.85744089972767], [2.352564, 48.85741979972767], [2.3525621, 48.857395999727686]]]} 127 | } 128 | 129 | - do: 130 | indices.refresh: {} 131 | 132 | # Test polygon simplification with douglas peucker 133 | # With zoom=1, polygon is reduced to a point 134 | - do: 135 | search: 136 | body: 137 | query: 138 | term: 139 | id: 1 140 | script_fields: 141 | simplified: 142 | script: 143 | source: geo_simplify 144 | lang: geo_extension_scripts 145 | params: 146 | field: "geo_shape_0.wkb" 147 | zoom: 1 148 | algorithm: DOUGLAS_PEUCKER 149 | 150 | - match: {hits.hits.0.fields.simplified.0.shape: "{\"type\":\"Point\",\"coordinates\":[-3.3889389,47.73770713],\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:0\"}}}" } 151 | 152 | # With topology preservation 153 | - do: 154 | search: 155 | body: 156 | query: 157 | term: 158 | id: 1 159 | script_fields: 160 | simplified: 161 | script: 162 | source: geo_simplify 163 | lang: geo_extension_scripts 164 | params: 165 | field: "geo_shape_0.wkb" 166 | zoom: 1 167 | algorithm: TOPOLOGY_PRESERVING 168 | 169 | - match: {hits.hits.0.fields.simplified.0.shape: "{\"type\":\"Polygon\",\"coordinates\":[[[-3.3889389,47.73770713],[-3.37778091,47.73851525],[-3.385849,47.74428718],[-3.3889389,47.73770713]]],\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:0\"}}}"} 170 | 171 | # simplification of a linestring 172 | - do: 173 | search: 174 | body: 175 | query: 176 | term: 177 | id: 2 # linestring 178 | script_fields: 179 | simplified: 180 | script: 181 | source: geo_simplify 182 | lang: geo_extension_scripts 183 | params: 184 | field: "geo_shape_0.wkb" 185 | zoom: 1 186 | algorithm: DOUGLAS_PEUCKER 187 | 188 | - match: {hits.hits.0.fields.simplified.0.shape: "{\"type\":\"LineString\",\"coordinates\":[[-3.38057041,47.7575746],[-3.38311851,47.75758181]],\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:0\"}}}"} 189 | 190 | # test with high zoom and TOPOLOGY_PRESERVING (exact same test as 40_geoshape_aggregation.yml one!) 191 | - do: 192 | search: 193 | body: 194 | query: 195 | term: 196 | id: 3 197 | script_fields: 198 | simplified: 199 | script: 200 | source: geo_simplify 201 | lang: geo_extension_scripts 202 | params: 203 | field: "geo_shape_0.wkb" 204 | zoom: 20 205 | algorithm: TOPOLOGY_PRESERVING 206 | 207 | # coordinates length must be 37. it's not possible to test this length because the shape is dumped as a text, so we're testing the full shape length here instead 208 | - length: {hits.hits.0.fields.simplified.0.shape: 935} 209 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s 90 | ' "$PWD" ) || exit 91 | 92 | # Use the maximum available, or set MAX_FD != -1 to use that value. 93 | MAX_FD=maximum 94 | 95 | warn () { 96 | echo "$*" 97 | } >&2 98 | 99 | die () { 100 | echo 101 | echo "$*" 102 | echo 103 | exit 1 104 | } >&2 105 | 106 | # OS specific support (must be 'true' or 'false'). 107 | cygwin=false 108 | msys=false 109 | darwin=false 110 | nonstop=false 111 | case "$( uname )" in #( 112 | CYGWIN* ) cygwin=true ;; #( 113 | Darwin* ) darwin=true ;; #( 114 | MSYS* | MINGW* ) msys=true ;; #( 115 | NONSTOP* ) nonstop=true ;; 116 | esac 117 | 118 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 119 | 120 | 121 | # Determine the Java command to use to start the JVM. 122 | if [ -n "$JAVA_HOME" ] ; then 123 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 124 | # IBM's JDK on AIX uses strange locations for the executables 125 | JAVACMD=$JAVA_HOME/jre/sh/java 126 | else 127 | JAVACMD=$JAVA_HOME/bin/java 128 | fi 129 | if [ ! -x "$JAVACMD" ] ; then 130 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 131 | 132 | Please set the JAVA_HOME variable in your environment to match the 133 | location of your Java installation." 134 | fi 135 | else 136 | JAVACMD=java 137 | if ! command -v java >/dev/null 2>&1 138 | then 139 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 140 | 141 | Please set the JAVA_HOME variable in your environment to match the 142 | location of your Java installation." 143 | fi 144 | fi 145 | 146 | # Increase the maximum file descriptors if we can. 147 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 148 | case $MAX_FD in #( 149 | max*) 150 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 151 | # shellcheck disable=SC2039,SC3045 152 | MAX_FD=$( ulimit -H -n ) || 153 | warn "Could not query maximum file descriptor limit" 154 | esac 155 | case $MAX_FD in #( 156 | '' | soft) :;; #( 157 | *) 158 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 159 | # shellcheck disable=SC2039,SC3045 160 | ulimit -n "$MAX_FD" || 161 | warn "Could not set maximum file descriptor limit to $MAX_FD" 162 | esac 163 | fi 164 | 165 | # Collect all arguments for the java command, stacking in reverse order: 166 | # * args from the command line 167 | # * the main class name 168 | # * -classpath 169 | # * -D...appname settings 170 | # * --module-path (only if needed) 171 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 172 | 173 | # For Cygwin or MSYS, switch paths to Windows format before running java 174 | if "$cygwin" || "$msys" ; then 175 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 176 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 177 | 178 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 179 | 180 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 181 | for arg do 182 | if 183 | case $arg in #( 184 | -*) false ;; # don't mess with options #( 185 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 186 | [ -e "$t" ] ;; #( 187 | *) false ;; 188 | esac 189 | then 190 | arg=$( cygpath --path --ignore --mixed "$arg" ) 191 | fi 192 | # Roll the args list around exactly as many times as the number of 193 | # args, so each arg winds up back in the position where it started, but 194 | # possibly modified. 195 | # 196 | # NB: a `for` loop captures its iteration list before it begins, so 197 | # changing the positional parameters here affects neither the number of 198 | # iterations, nor the values presented in `arg`. 199 | shift # remove old arg 200 | set -- "$@" "$arg" # push replacement arg 201 | done 202 | fi 203 | 204 | 205 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 206 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 207 | 208 | # Collect all arguments for the java command: 209 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 210 | # and any embedded shellness will be escaped. 211 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 212 | # treated as '${Hostname}' itself on the command line. 213 | 214 | set -- \ 215 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 216 | -classpath "$CLASSPATH" \ 217 | org.gradle.wrapper.GradleWrapperMain \ 218 | "$@" 219 | 220 | # Stop when "xargs" is not available. 221 | if ! command -v xargs >/dev/null 2>&1 222 | then 223 | die "xargs is not available" 224 | fi 225 | 226 | # Use "xargs" to parse quoted args. 227 | # 228 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 229 | # 230 | # In Bash we could simply go: 231 | # 232 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 233 | # set -- "${ARGS[@]}" "$@" 234 | # 235 | # but POSIX shell has neither arrays nor command substitution, so instead we 236 | # post-process each arg (as a line of input to sed) to backslash-escape any 237 | # character that might be a shell metacharacter, then use eval to reverse 238 | # that process (while maintaining the separation between arguments), and wrap 239 | # the whole thing up as a single "set" statement. 240 | # 241 | # This will of course break if any of these variables contains a newline or 242 | # an unmatched quote. 243 | # 244 | 245 | eval "set -- $( 246 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 247 | xargs -n1 | 248 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 249 | tr '\n' ' ' 250 | )" '"$@"' 251 | 252 | exec "$JAVACMD" "$@" 253 | -------------------------------------------------------------------------------- /src/main/java/org/opendatasoft/elasticsearch/ingest/GeoExtensionProcessor.java: -------------------------------------------------------------------------------- 1 | package org.opendatasoft.elasticsearch.ingest; 2 | 3 | import org.apache.lucene.util.BytesRef; 4 | import org.elasticsearch.common.geo.GeoJson; 5 | import org.elasticsearch.common.geo.GeoPoint; 6 | import org.elasticsearch.common.geo.GeometryNormalizer; 7 | import org.elasticsearch.common.geo.GeometryParser; 8 | import org.elasticsearch.common.geo.Orientation; 9 | import org.elasticsearch.common.regex.Regex; 10 | import org.elasticsearch.geometry.utils.WellKnownBinary; 11 | import org.elasticsearch.geometry.utils.WellKnownText; 12 | import org.elasticsearch.ingest.AbstractProcessor; 13 | import org.elasticsearch.ingest.ConfigurationUtils; 14 | import org.elasticsearch.ingest.IngestDocument; 15 | import org.elasticsearch.ingest.Processor; 16 | import org.locationtech.jts.geom.Coordinate; 17 | import org.locationtech.jts.geom.GeometryFactory; 18 | import org.locationtech.jts.geom.PrecisionModel; 19 | import org.locationtech.jts.io.ParseException; 20 | import org.locationtech.jts.io.WKTWriter; 21 | import org.opendatasoft.elasticsearch.plugin.GeoUtils; 22 | 23 | import java.io.IOException; 24 | import java.nio.ByteOrder; 25 | import java.util.ArrayList; 26 | import java.util.Arrays; 27 | import java.util.List; 28 | import java.util.Map; 29 | 30 | public class GeoExtensionProcessor extends AbstractProcessor { 31 | public static final String TYPE = "geo_extension"; 32 | 33 | private final String field; 34 | private final String path; 35 | private final Boolean keepShape; 36 | private final String shapeField; 37 | private final String fixedField; 38 | private final String wkbField; 39 | private final String hashField; 40 | private final String typeField; 41 | private final String areaField; 42 | private final String bboxField; 43 | private final String centroidField; 44 | 45 | private final GeometryFactory geomFactory; 46 | private final WKTWriter wktWriter; 47 | 48 | private GeoExtensionProcessor( 49 | String tag, 50 | String description, 51 | String field, 52 | String path, 53 | Boolean keepShape, 54 | String shapeField, 55 | String fixedField, 56 | String wkbField, 57 | String hashField, 58 | String typeField, 59 | String areaField, 60 | String bboxField, 61 | String centroidField 62 | ) { 63 | super(tag, description); 64 | this.field = field; 65 | this.path = path; 66 | this.keepShape = keepShape; 67 | this.shapeField = shapeField; 68 | this.fixedField = fixedField; 69 | this.wkbField = wkbField; 70 | this.hashField = hashField; 71 | this.typeField = typeField; 72 | this.areaField = areaField; 73 | this.bboxField = bboxField; 74 | this.centroidField = centroidField; 75 | 76 | PrecisionModel precisionModel = new PrecisionModel(PrecisionModel.FLOATING); 77 | this.geomFactory = new GeometryFactory(precisionModel, 0); 78 | 79 | this.wktWriter = new WKTWriter(); 80 | } 81 | 82 | @SuppressWarnings("unchecked") 83 | private List getGeoShapeFieldsFromDoc(IngestDocument ingestDocument) { 84 | List fields = new ArrayList<>(); 85 | 86 | Map baseMap; 87 | if (path != null) { 88 | baseMap = ingestDocument.getFieldValue(this.path, Map.class); 89 | } else { 90 | baseMap = ingestDocument.getSourceAndMetadata(); 91 | } 92 | 93 | for (String fieldName : baseMap.keySet()) { 94 | if (Regex.simpleMatch(field, fieldName)) { 95 | if (path != null) { 96 | fieldName = path + "." + fieldName; 97 | } 98 | fields.add(fieldName); 99 | } 100 | } 101 | 102 | return fields; 103 | } 104 | 105 | // WARNING: I wonder if some stuff we do in our plugin can be replaced by the x-pack spatial 106 | // GeoShapeWithDocValuesFieldMapper index mapper 107 | 108 | @Override 109 | public IngestDocument execute(IngestDocument ingestDocument) throws IOException, ParseException { 110 | GeometryParser geoParser = new GeometryParser(true, true, true); 111 | List geo_objects_list = getGeoShapeFieldsFromDoc(ingestDocument); 112 | for (String geoShapeField : geo_objects_list) { 113 | 114 | Object geoShapeObject = ingestDocument.getFieldValue(geoShapeField, Object.class); 115 | 116 | if (geoShapeObject == null) { 117 | continue; 118 | } 119 | 120 | // Parse the GeoJSON geometry from the ingestDoc 121 | org.elasticsearch.geometry.Geometry geom = geoParser.parseGeometry(geoShapeObject); 122 | 123 | // Try to remove some duplicated coordinates. Duplicated coordinates don't make the geom invalid 124 | // but the GeometryNormalizer won't accept duplicated coords. 125 | try { 126 | geom = GeoUtils.removeDuplicateCoordinates(geom); 127 | } catch (Throwable e) { 128 | throw new IllegalArgumentException("unable to parse the geometry [" + WellKnownText.toWKT(geom) + "]" + e.getMessage()); 129 | } 130 | 131 | // Can break geometries that cross the dateline 132 | org.elasticsearch.geometry.Geometry fixedGeom = GeometryNormalizer.apply(Orientation.RIGHT, geom); 133 | String altWKT = WellKnownText.toWKT(fixedGeom); 134 | 135 | ingestDocument.removeField(geoShapeField); 136 | 137 | if (keepShape) { 138 | ingestDocument.setFieldValue(geoShapeField + "." + shapeField, geoShapeObject); 139 | } 140 | 141 | if (fixedField != null) { 142 | ingestDocument.setFieldValue(geoShapeField + "." + fixedField, altWKT); 143 | } 144 | 145 | String geomType = GeoJson.getGeoJsonName(fixedGeom); 146 | 147 | // compute and add extra geo sub-fields 148 | // NOTE: elasticsearch.common.geo encodes with Little-Endianess. 149 | byte[] wkb = WellKnownBinary.toWKB(fixedGeom, ByteOrder.LITTLE_ENDIAN); 150 | 151 | if (hashField != null) ingestDocument.setFieldValue( 152 | geoShapeField + ".hash", 153 | String.valueOf(GeoUtils.getHashFromWKB(new BytesRef(wkb))) 154 | ); 155 | if (wkbField != null) ingestDocument.setFieldValue(geoShapeField + "." + wkbField, wkb); 156 | if (typeField != null) ingestDocument.setFieldValue(geoShapeField + "." + typeField, geomType); 157 | if (areaField != null) ingestDocument.setFieldValue(geoShapeField + "." + areaField, GeoUtils.getArea(fixedGeom)); 158 | if (centroidField != null) ingestDocument.setFieldValue( 159 | geoShapeField + "." + centroidField, 160 | GeoUtils.getCentroidFromGeom(fixedGeom) 161 | ); 162 | if (bboxField != null) { 163 | Coordinate[] coords = GeoUtils.getEnvelope(fixedGeom).getCoordinates(); 164 | if (coords.length >= 4) { 165 | ingestDocument.setFieldValue(geoShapeField + "." + bboxField, GeoUtils.getBboxFromCoords(coords)); 166 | } else if (coords.length == 1) { 167 | GeoPoint point = new GeoPoint( 168 | org.elasticsearch.common.geo.GeoUtils.normalizeLat(coords[0].y), 169 | org.elasticsearch.common.geo.GeoUtils.normalizeLon(coords[0].x) 170 | ); 171 | ingestDocument.setFieldValue(geoShapeField + "." + bboxField, Arrays.asList(point, point)); 172 | } 173 | } 174 | } 175 | return ingestDocument; 176 | } 177 | 178 | @Override 179 | public String getType() { 180 | return TYPE; 181 | } 182 | 183 | public static final class Factory implements Processor.Factory { 184 | @Override 185 | public GeoExtensionProcessor create( 186 | Map registry, 187 | String processorTag, 188 | String description, 189 | Map config 190 | ) { 191 | String field = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "field"); 192 | String path = ConfigurationUtils.readOptionalStringProperty(TYPE, processorTag, config, "path"); 193 | 194 | boolean keep_shape = ConfigurationUtils.readBooleanProperty(TYPE, processorTag, config, "keep_original_shape", true); 195 | String shapeField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "shape_field", "shape"); 196 | 197 | boolean fix = ConfigurationUtils.readBooleanProperty(TYPE, processorTag, config, "fix_shape", true); 198 | String fixedField = null; 199 | if (fix) { 200 | fixedField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "fixed_field", "fixed_shape"); 201 | } 202 | 203 | boolean needWkb = ConfigurationUtils.readBooleanProperty(TYPE, processorTag, config, "wkb", true); 204 | String wkbField = null; 205 | if (needWkb) { 206 | wkbField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "wkb_field", "wkb"); 207 | } 208 | 209 | boolean needHash = ConfigurationUtils.readBooleanProperty(TYPE, processorTag, config, "hash", true); 210 | String hashField = null; 211 | if (needHash) { 212 | hashField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "hash_field", "hash"); 213 | } 214 | 215 | boolean needType = ConfigurationUtils.readBooleanProperty(TYPE, processorTag, config, "type", true); 216 | String typeField = null; 217 | if (needType) { 218 | typeField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "type_field", "type"); 219 | } 220 | 221 | boolean needArea = ConfigurationUtils.readBooleanProperty(TYPE, processorTag, config, "area", true); 222 | String areaField = null; 223 | if (needArea) { 224 | areaField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "area_field", "area"); 225 | } 226 | 227 | boolean needBbox = ConfigurationUtils.readBooleanProperty(TYPE, processorTag, config, "bbox", true); 228 | String bboxField = null; 229 | if (needBbox) { 230 | bboxField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "bbox_field", "bbox"); 231 | } 232 | 233 | boolean needCentroid = ConfigurationUtils.readBooleanProperty(TYPE, processorTag, config, "centroid", true); 234 | String centroidField = null; 235 | if (needCentroid) { 236 | centroidField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "centroid_field", "centroid"); 237 | } 238 | 239 | return new GeoExtensionProcessor( 240 | processorTag, 241 | description, 242 | field, 243 | path, 244 | keep_shape, 245 | shapeField, 246 | fixedField, 247 | wkbField, 248 | hashField, 249 | typeField, 250 | areaField, 251 | bboxField, 252 | centroidField 253 | ); 254 | } 255 | } 256 | } 257 | -------------------------------------------------------------------------------- /src/main/java/org/opendatasoft/elasticsearch/search/aggregations/bucket/geoshape/GeoShapeBuilder.java: -------------------------------------------------------------------------------- 1 | package org.opendatasoft.elasticsearch.search.aggregations.bucket.geoshape; 2 | 3 | import org.elasticsearch.TransportVersion; 4 | import org.elasticsearch.TransportVersions; 5 | import org.elasticsearch.common.io.stream.StreamInput; 6 | import org.elasticsearch.common.io.stream.StreamOutput; 7 | import org.elasticsearch.search.aggregations.AggregationBuilder; 8 | import org.elasticsearch.search.aggregations.AggregatorFactories; 9 | import org.elasticsearch.search.aggregations.AggregatorFactories.Builder; 10 | import org.elasticsearch.search.aggregations.AggregatorFactory; 11 | import org.elasticsearch.search.aggregations.support.AggregationContext; 12 | import org.elasticsearch.search.aggregations.support.CoreValuesSourceType; 13 | import org.elasticsearch.search.aggregations.support.ValuesSourceAggregationBuilder; 14 | import org.elasticsearch.search.aggregations.support.ValuesSourceAggregatorFactory; 15 | import org.elasticsearch.search.aggregations.support.ValuesSourceConfig; 16 | import org.elasticsearch.search.aggregations.support.ValuesSourceRegistry; 17 | import org.elasticsearch.search.aggregations.support.ValuesSourceType; 18 | import org.elasticsearch.xcontent.ObjectParser; 19 | import org.elasticsearch.xcontent.ParseField; 20 | import org.elasticsearch.xcontent.XContentBuilder; 21 | import org.elasticsearch.xcontent.XContentParser; 22 | import org.opendatasoft.elasticsearch.plugin.GeoUtils; 23 | 24 | import java.io.IOException; 25 | import java.util.Arrays; 26 | import java.util.Collections; 27 | import java.util.List; 28 | import java.util.Locale; 29 | import java.util.Map; 30 | import java.util.Objects; 31 | 32 | /** 33 | * The builder of the aggregatorFactory. Also implements the parsing of the request. 34 | */ 35 | public class GeoShapeBuilder extends ValuesSourceAggregationBuilder 36 | /*implements MultiBucketAggregationBuilder*/ { 37 | public static final String NAME = "geoshape"; 38 | 39 | public static final ValuesSourceRegistry.RegistryKey REGISTRY_KEY = new ValuesSourceRegistry.RegistryKey<>( 40 | NAME, 41 | GeoShapeAggregatorSupplier.class 42 | ); 43 | 44 | private static final ParseField OUTPUT_FORMAT_FIELD = new ParseField("output_format"); 45 | public static final ParseField SIMPLIFY_FIELD = new ParseField("simplify"); 46 | public static final ParseField SIZE_FIELD = new ParseField("size"); 47 | public static final ParseField SHARD_SIZE_FIELD = new ParseField("shard_size"); 48 | 49 | public static final GeoShapeAggregator.BucketCountThresholds DEFAULT_BUCKET_COUNT_THRESHOLDS = 50 | new GeoShapeAggregator.BucketCountThresholds(10, -1); 51 | private static final ObjectParser PARSER; 52 | static { 53 | PARSER = new ObjectParser<>(GeoShapeBuilder.NAME); 54 | ValuesSourceAggregationBuilder.declareFields(PARSER, true, true, false); 55 | PARSER.declareString(GeoShapeBuilder::output_format, OUTPUT_FORMAT_FIELD); 56 | PARSER.declareObjectArray( 57 | GeoShapeBuilder::simplify_keys, 58 | (p, c) -> SimplifyKeysParser.Parser.parseSimplifyParam(p), 59 | SIMPLIFY_FIELD 60 | ); 61 | PARSER.declareInt(GeoShapeBuilder::size, SIZE_FIELD); 62 | PARSER.declareInt(GeoShapeBuilder::shardSize, SHARD_SIZE_FIELD); 63 | } 64 | 65 | public static GeoShapeBuilder parse(XContentParser parser, String aggregationName) throws IOException { 66 | return PARSER.parse(parser, new GeoShapeBuilder(aggregationName), null); 67 | } 68 | 69 | @Override 70 | public TransportVersion getMinimalSupportedVersion() { 71 | return TransportVersion.zero(); 72 | } 73 | 74 | static class SimplifyKeysParser { 75 | static class Parser { 76 | static List parseSimplifyParam(XContentParser parser) throws IOException { 77 | XContentParser.Token token; 78 | int zoom = -1; 79 | String algorithm = null; 80 | 81 | String currentFieldName = null; 82 | while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { 83 | if (token == XContentParser.Token.FIELD_NAME) { 84 | currentFieldName = parser.currentName(); 85 | } else if (token == XContentParser.Token.VALUE_NUMBER) { 86 | if ("zoom".equals(currentFieldName)) { 87 | zoom = parser.intValue(); 88 | } 89 | } else if (token == XContentParser.Token.VALUE_STRING) { 90 | if ("algorithm".equals(currentFieldName)) { 91 | algorithm = parser.text(); 92 | } 93 | } 94 | } 95 | if ((zoom != -1) && (algorithm != null)) return Arrays.asList(zoom, algorithm); 96 | else return Collections.emptyList(); 97 | } 98 | } 99 | } 100 | 101 | public static final GeoUtils.OutputFormat DEFAULT_OUTPUT_FORMAT = GeoUtils.OutputFormat.GEOJSON; 102 | private boolean must_simplify = false; 103 | public static final int DEFAULT_ZOOM = 0; 104 | public static final GeoShape.Algorithm DEFAULT_ALGORITHM = GeoShape.Algorithm.DOUGLAS_PEUCKER; 105 | private GeoUtils.OutputFormat output_format = DEFAULT_OUTPUT_FORMAT; 106 | private int simplify_zoom = DEFAULT_ZOOM; 107 | private GeoShape.Algorithm simplify_algorithm = DEFAULT_ALGORITHM; 108 | private GeoShapeAggregator.BucketCountThresholds bucketCountThresholds = new GeoShapeAggregator.BucketCountThresholds( 109 | DEFAULT_BUCKET_COUNT_THRESHOLDS 110 | ); 111 | 112 | private GeoShapeBuilder(String name) { 113 | super(name); 114 | } 115 | 116 | /** 117 | * Read from a stream 118 | * 119 | */ 120 | public GeoShapeBuilder(StreamInput in) throws IOException { 121 | super(in); 122 | bucketCountThresholds = new GeoShapeAggregator.BucketCountThresholds(in); 123 | must_simplify = in.readBoolean(); 124 | output_format = GeoUtils.OutputFormat.valueOf(in.readString()); 125 | simplify_zoom = in.readInt(); 126 | simplify_algorithm = GeoShape.Algorithm.valueOf(in.readString()); 127 | } 128 | 129 | /** 130 | * Write to a stream 131 | */ 132 | @Override 133 | protected void innerWriteTo(StreamOutput out) throws IOException { 134 | bucketCountThresholds.writeTo(out); 135 | out.writeBoolean(must_simplify); 136 | out.writeString(output_format.name()); 137 | out.writeInt(simplify_zoom); 138 | out.writeString(simplify_algorithm.name()); 139 | } 140 | 141 | private GeoShapeBuilder(GeoShapeBuilder clone, Builder factoriesBuilder, Map metaData) { 142 | super(clone, factoriesBuilder, metaData); 143 | output_format = clone.output_format; 144 | must_simplify = clone.must_simplify; 145 | simplify_zoom = clone.simplify_zoom; 146 | simplify_algorithm = clone.simplify_algorithm; 147 | this.bucketCountThresholds = new GeoShapeAggregator.BucketCountThresholds(clone.bucketCountThresholds); 148 | } 149 | 150 | @Override 151 | protected AggregationBuilder shallowCopy(AggregatorFactories.Builder factoriesBuilder, Map metaData) { 152 | return new GeoShapeBuilder(this, factoriesBuilder, metaData); 153 | } 154 | 155 | @Override 156 | public BucketCardinality bucketCardinality() { 157 | return null; 158 | } 159 | 160 | private GeoShapeBuilder output_format(String output_format) { 161 | this.output_format = GeoUtils.OutputFormat.valueOf(output_format.toUpperCase(Locale.getDefault())); 162 | return this; 163 | } 164 | 165 | @SuppressWarnings("unchecked") 166 | private GeoShapeBuilder simplify_keys(List simplify) { 167 | List simplify_keys = (List) simplify.get(0); 168 | if (!simplify_keys.isEmpty()) { 169 | this.must_simplify = true; 170 | this.simplify_zoom = (int) simplify_keys.get(0); 171 | this.simplify_algorithm = GeoShape.Algorithm.valueOf(((String) simplify_keys.get(1)).toUpperCase(Locale.getDefault())); 172 | } 173 | return this; 174 | } 175 | 176 | @Override 177 | protected ValuesSourceType defaultValueSourceType() { 178 | return CoreValuesSourceType.KEYWORD; 179 | } 180 | 181 | /** 182 | * Sets the size - indicating how many term buckets should be returned 183 | * (defaults to 10) 184 | */ 185 | public GeoShapeBuilder size(int size) { 186 | if (size <= 0) { 187 | throw new IllegalArgumentException("[size] must be greater than 0. Found [" + size + "] in [" + name + "]"); 188 | } 189 | bucketCountThresholds.setRequiredSize(size); 190 | return this; 191 | } 192 | 193 | /** 194 | * Sets the shard_size - indicating the number of term buckets each shard 195 | * will return to the coordinating node (the node that coordinates the 196 | * search execution). The higher the shard size is, the more accurate the 197 | * results are. 198 | */ 199 | public GeoShapeBuilder shardSize(int shardSize) { 200 | if (shardSize <= 0) { 201 | throw new IllegalArgumentException("[shardSize] must be greater than 0. Found [" + shardSize + "] in [" + name + "]"); 202 | } 203 | bucketCountThresholds.setShardSize(shardSize); 204 | return this; 205 | } 206 | 207 | @Override 208 | protected ValuesSourceAggregatorFactory innerBuild( 209 | AggregationContext queryShardContext, 210 | ValuesSourceConfig config, 211 | AggregatorFactory parent, 212 | AggregatorFactories.Builder subFactoriesBuilder 213 | ) throws IOException { 214 | return new GeoShapeAggregatorFactory( 215 | name, 216 | config, 217 | output_format, 218 | must_simplify, 219 | simplify_zoom, 220 | simplify_algorithm, 221 | bucketCountThresholds, 222 | queryShardContext, 223 | parent, 224 | subFactoriesBuilder, 225 | metadata 226 | ); 227 | } 228 | 229 | @Override 230 | protected XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException { 231 | builder.startObject(); 232 | 233 | if (!output_format.equals(DEFAULT_OUTPUT_FORMAT)) { 234 | builder.field(OUTPUT_FORMAT_FIELD.getPreferredName(), output_format); 235 | } 236 | 237 | return builder.endObject(); 238 | } 239 | 240 | /** 241 | * Used for caching requests, amongst other things. 242 | */ 243 | @Override 244 | public int hashCode() { 245 | return Objects.hash(super.hashCode(), output_format, must_simplify, simplify_zoom, simplify_algorithm, bucketCountThresholds); 246 | } 247 | 248 | @Override 249 | public boolean equals(Object obj) { 250 | if (this == obj) return true; 251 | if (obj == null || getClass() != obj.getClass()) return false; 252 | if (!super.equals(obj)) return false; 253 | 254 | GeoShapeBuilder other = (GeoShapeBuilder) obj; 255 | return Objects.equals(output_format, other.output_format) 256 | && Objects.equals(must_simplify, other.must_simplify) 257 | && Objects.equals(simplify_zoom, other.simplify_zoom) 258 | && Objects.equals(simplify_algorithm, other.simplify_algorithm) 259 | && Objects.equals(bucketCountThresholds, other.bucketCountThresholds); 260 | } 261 | 262 | @Override 263 | public String getType() { 264 | return NAME; 265 | } 266 | 267 | public static void registerAggregators(ValuesSourceRegistry.Builder builder) { 268 | builder.register(GeoShapeBuilder.REGISTRY_KEY, CoreValuesSourceType.KEYWORD, GeoShapeAggregator::new, true); 269 | } 270 | } 271 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Elasticsearch GeoShape Plugin 2 | 3 | 4 | This plugin can be used to index geo_shape objects in elasticsearch, then aggregate and/or script-simplify them. 5 | 6 | This is an `Ingest`, `Search` and `Script` plugin. 7 | 8 | 9 | ## Installation 10 | 11 | Current supported version is Elasticsearch 8.x. 12 | You can find past releases [here](https://github.com/opendatasoft/elasticsearch-plugin-geoshape/releases). 13 | 14 | The first 3 digits of the plugin version is the corresponding Elasticsearch version. The last digit is used for plugin versioning. 15 | 16 | To install it, launch this command in Elasticsearch directory replacing the url by the correct link for your Elasticsearch version (see table) 17 | `bin/elasticsearch-plugin install https://github.com/opendatasoft/elasticsearch-plugin-geoshape/releases/download/v8.19.6.0/elasticsearch-plugin-geoshape-8.19.6.0.zip"` 18 | 19 | 20 | ## Build 21 | 22 | Built with Java 17 and Gradle 8.10.2 (but you should use the packaged gradlew included in this repo anyway). 23 | 24 | 25 | ## Usage 26 | 27 | ### Ingest processor and indexing 28 | 29 | A new processor `geo_extension` adds custom fields to the desired geo_shape data object at ingest time. 30 | 31 | #### Params 32 | 33 | Processor name: `geo_extension`. 34 | 35 | |Name|Required|Default|Description| 36 | |----|--------|-------|-----------| 37 | | `field` | yes | - | The geo shape field to use. This parameter accepts wildcard to match multiple `geo_shape` fields 38 | | `path` | no | - | The field that contains the field to expand. When using wildcard in `field`, matching will be done under this path only 39 | | `keep_original_shape` | no | `true` | Keep the original unfixed shape in a `shape` field 40 | | `shape_field` | no | `shape` | Name of sub `shape` field 41 | | `fix_shape` | no | `true` | Fix invalid shape. For the moment it only fixes duplicate consecutive coordinates in polygon (https://github.com/elastic/elasticsearch/issues/14014) 42 | | `fixed_field` | no | `fixed_shape` | Name of sub `fixed_shape` field 43 | | `wkb` | no | `true` | Compute wkb from shape field 44 | | `wkb_field` | no | `wkb` | name of wkb subfield 45 | | `type` | no | `true` | Compute geo shape type (Polygon, point, LineString, ...) 46 | | `type_field` | no | `type` | name of type subfield 47 | | `area` | no | `true` | Compute area of shape 48 | | `area_field` | no | `area` | name of `area` subfield 49 | | `bbox` | no | `true` | Compute geo_point array containing topLeft and bottomRight points of shape envelope 50 | | `bbox_field` | no | `bbox` | name of `bbox` subfield 51 | | `centroid` | no | `true` | Compute geo_point representing shape centroid 52 | | `centroid_field` | no | `centroid` | name of `centroid` subfield 53 | | `hash` | no | `true` | Compute shape digest to perform exact request on shape (in other words: used as a primary key. we may want to use the wkt in the future?) 54 | | `hash_field` | no | `hash` | name of `hash` subfield 55 | 56 | 57 | #### Example 58 | ``` 59 | 60 | PUT _ingest/pipeline/geo_extension 61 | { 62 | "description": "Add extra geo fields to geo_shape objects.", 63 | "processors": [ 64 | { 65 | "geo_extension": { 66 | "field": "geoshape_*" 67 | } 68 | } 69 | ] 70 | } 71 | PUT main 72 | { 73 | "mappings": { 74 | "dynamic_templates": [ 75 | { 76 | "geoshapes": { 77 | "match": "geoshape_*", 78 | "mapping": { 79 | "properties": { 80 | "geoshape": {"type": "geo_shape"}, 81 | "hash": {"type": "keyword"}, 82 | "wkb": {"type": "binary", "doc_values": true}, 83 | "type": {"type": "keyword"}, 84 | "area": {"type": "half_float"}, 85 | "bbox": {"type": "geo_point"}, 86 | "centroid": {"type": "geo_point"} 87 | } 88 | } 89 | } 90 | } 91 | ] 92 | } 93 | } 94 | GET main/_mapping 95 | ``` 96 | 97 | Result: 98 | ``` 99 | { 100 | "main": { 101 | "mappings": { 102 | "_doc": { 103 | "dynamic_templates": [ 104 | { 105 | "geoshapes": { 106 | "match": "geoshape_*", 107 | "mapping": { 108 | "properties": { 109 | "geoshape": { 110 | "type": "geo_shape" 111 | }, 112 | "hash": { 113 | "type": "keyword" 114 | }, 115 | "wkb": { 116 | "type": "binary", 117 | "doc_values": true 118 | }, 119 | "type": { 120 | "type": "keyword" 121 | }, 122 | "area": { 123 | "type": "half_float" 124 | }, 125 | "bbox": { 126 | "type": "geo_point" 127 | }, 128 | "centroid": { 129 | "type": "geo_point" 130 | } 131 | } 132 | } 133 | } 134 | } 135 | ] 136 | } 137 | } 138 | } 139 | } 140 | ``` 141 | 142 | Document indexing with shape fixing: 143 | ``` 144 | POST main/_doc?pipeline=geo_extension 145 | { 146 | "geoshape_0": { 147 | "type": "Polygon", 148 | "coordinates": [ 149 | [ 150 | [ 151 | 1.6809082031249998, 152 | 49.05227025601607 153 | ], 154 | [ 155 | 2.021484375, 156 | 48.596592251456705 157 | ], 158 | [ 159 | 2.021484375, 160 | 48.596592251456705 161 | ], 162 | [ 163 | 3.262939453125, 164 | 48.922499263758255 165 | ], 166 | [ 167 | 2.779541015625, 168 | 49.196064000723794 169 | ], 170 | [ 171 | 2.0654296875, 172 | 49.23194729854559 173 | ], 174 | [ 175 | 1.6809082031249998, 176 | 49.05227025601607 177 | ] 178 | ] 179 | ] 180 | } 181 | } 182 | GET main/_search 183 | ``` 184 | 185 | Result: 186 | ``` 187 | "hits": [ 188 | { 189 | "_source": { 190 | "geoshape_0": { 191 | "area": 0.594432056845634, 192 | "centroid": { 193 | "lat": 48.95553463671871, 194 | "lon": 2.3829210191713015 195 | }, 196 | "bbox": [ 197 | { 198 | "lat": 48.596592251456705, 199 | "lon": 1.6809082031249998 200 | }, 201 | { 202 | "lat": 49.23194729854559, 203 | "lon": 3.262939453125 204 | } 205 | ], 206 | "type": "Polygon", 207 | "geoshape": { 208 | "coordinates": [ 209 | [ 210 | [ 211 | 1.6809082031249998, 212 | 49.05227025601607 213 | ], 214 | [ 215 | 2.021484375, 216 | 48.596592251456705 217 | ], 218 | [ 219 | 3.262939453125, 220 | 48.922499263758255 221 | ], 222 | [ 223 | 2.779541015625, 224 | 49.196064000723794 225 | ], 226 | [ 227 | 2.0654296875, 228 | 49.23194729854559 229 | ], 230 | [ 231 | 1.6809082031249998, 232 | 49.05227025601607 233 | ] 234 | ] 235 | ], 236 | "type": "Polygon" 237 | }, 238 | "hash": "-5012816342630707936", 239 | "wkb": "AAAAAAMAAAABAAAABkAALAAAAAAAQEhMXSKIhttAChqAAAAAAEBIdhR0tDaAQAY8gAAAAABASJkYoAuEDEAAhgAAAAAAQEidsHL20w4/+uT//////0BIhrDKsBJAQAAsAAAAAABASExdIoiG2w==" 240 | } 241 | } 242 | } 243 | ``` 244 | Note that the duplicated point has been deduplicated. 245 | 246 | 247 | 248 | ### Geoshape aggregation 249 | 250 | This aggregation creates a bucket for each input shape (based on the hash of its WKB representation) and compute a simplified version of the shape in the bucket. 251 | The simplification part is similar to what is done with the simplify script. 252 | The `size` parameter allows you to retain only the biggest (longer) N shapes. 253 | Moreover, compared to regular search results, results of an aggregation can be [cached by ElasticSearch](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html#agg-caches). 254 | 255 | 256 | 257 | #### Params 258 | 259 | - `field` (mandatory): the field used for aggregating. Must be of wkb type. E.g.: "geoshape_0.wkb". 260 | - `output_format`: the output_format in [`geojson`, `wkt`, `wkb`]. Default to `geojson`. 261 | - `simplify`: 262 | - `zoom`: the zoom level in range [0, 20]. 0 is the most simplified and 20 is the least. Default to 0. 263 | - `algorithm`: simplify algorithm in [`DOUGLAS_PEUCKER`, `TOPOLOGY_PRESERVING`]. Default to `DOUGLAS_PEUCKER`. 264 | - `size`: can be set to define how many buckets should be returned. See elasticsearch official terms aggregation documentation for more explanation. Buckets are ordered by the length (perimeter for polygons) of their shape, longer shapes first. 265 | - `shard_size`: can be used to minimize the extra work that comes with bigger requested `size`. See elasticsearch official terms aggregation documentation for more explanation. 266 | 267 | 268 | #### Example 269 | 270 | ``` 271 | GET main/_search?size=0 272 | { 273 | "aggs": { 274 | "geo_preview": { 275 | "geoshape": { 276 | "field": "geoshape_0.wkb", 277 | "output_format": "wkb", 278 | "simplify": { 279 | "zoom": 8, 280 | "algorithm": "douglas_peucker" 281 | }, 282 | "size": 10, 283 | "shard_size": 10 284 | } 285 | } 286 | } 287 | } 288 | ``` 289 | 290 | Result: 291 | ``` 292 | "aggregations": { 293 | "geo_preview": { 294 | "buckets": [ 295 | { 296 | "key": "AAAAAAMAAAABAAAABkAALAAAAAAAQEhMXSKIhts/+uT//////0BIhrDKsBJAQACGAAAAAABASJ2wcvbTDkAGPIAAAAAAQEiZGKALhAxAChqAAAAAAEBIdhR0tDaAQAAsAAAAAABASExdIoiG2w==", 297 | "digest": "-5012816342630707936", 298 | "type": "Polygon", 299 | "doc_count": 1 300 | } 301 | ] 302 | } 303 | } 304 | ``` 305 | 306 | 307 | 308 | 309 | ### Geoshape simplify script 310 | 311 | Search script for simplifying shapes dynamically. 312 | 313 | 314 | #### Script params 315 | 316 | - `field`: the field to apply the script to. 317 | - `zoom`: the zoom level in range [0, 20]. 0 is the most simplified and 20 is the least. Default to 0. 318 | - `algorithm`: simplify algorithm in [`DOUGLAS_PEUCKER`, `TOPOLOGY_PRESERVING`]. Default to `DOUGLAS_PEUCKER`. 319 | - `output_format`: the output_format in [`geojson`, `wkt`, `wkb`]. Default to `geojson`. 320 | 321 | 322 | #### Example 323 | 324 | ``` 325 | GET main/_search 326 | { 327 | "script_fields": { 328 | "simplified_shape": { 329 | "script": { 330 | "lang": "geo_extension_scripts", 331 | "source": "geo_simplify", 332 | "params": { 333 | "field": "geoshape_0", 334 | "zoom": 8, 335 | "output_format": "wkt" 336 | } 337 | } 338 | } 339 | } 340 | } 341 | ``` 342 | 343 | Result: 344 | ``` 345 | "hits": [ 346 | { 347 | "fields": { 348 | "simplified_shape": [ 349 | { 350 | "real_type": "Polygon", 351 | "geom": "POLYGON ((2.021484375 48.596592251456705, 1.6809082031249998 49.05227025601607, 2.0654296875 49.23194729854559, 2.779541015625 49.196064000723794, 3.262939453125 48.922499263758255, 2.021484375 48.596592251456705))", 352 | "type": "Polygon" 353 | } 354 | ] 355 | } 356 | } 357 | ``` 358 | 359 | ## Development Environment Setup 360 | 361 | Built with Java 17 and Gradle 8.10.2. 362 | 363 | Build the plugin using gradle: 364 | 365 | ```sh 366 | ./gradlew build 367 | ``` 368 | 369 | or 370 | ```sh 371 | ./gradlew assemble # (to avoid the test suite) 372 | ``` 373 | 374 | Then you can find the current version of the plugin at e.g. `elasticsearch-plugin-geoshape-7.17.z.d.zip` 375 | 376 | In case you have to upgrade Gradle, you can do it with `./gradlew wrapper --gradler-version x.y.z`. 377 | 378 | Then the following command will start a dockerized ES and will install the previously built plugin: 379 | 380 | ```sh 381 | docker compose up 382 | ``` 383 | 384 | Check the Elasticsearch instance at `localhost:9200` and the plugin version with `localhost:9200/_cat/plugins`. 385 | 386 | Please be careful during development: you'll need to manually rebuild the .zip using `./gradlew build` on each code 387 | change before running `docker-compose` up again. 388 | 389 | > NOTE: In `docker-compose.yml` you can uncomment the debug env and attach a REMOTE JVM on `*:5005` to debug the plugin. 390 | 391 | ## License 392 | 393 | This software is under AGPL (GNU Affero General Public License) 394 | -------------------------------------------------------------------------------- /src/main/java/org/opendatasoft/elasticsearch/search/aggregations/bucket/geoshape/InternalGeoShape.java: -------------------------------------------------------------------------------- 1 | package org.opendatasoft.elasticsearch.search.aggregations.bucket.geoshape; 2 | 3 | import org.apache.lucene.util.BytesRef; 4 | import org.apache.lucene.util.PriorityQueue; 5 | import org.elasticsearch.common.io.stream.StreamInput; 6 | import org.elasticsearch.common.io.stream.StreamOutput; 7 | import org.elasticsearch.common.io.stream.Writeable; 8 | import org.elasticsearch.common.util.LongObjectPagedHashMap; 9 | import org.elasticsearch.search.aggregations.Aggregation; 10 | import org.elasticsearch.search.aggregations.AggregationReduceContext; 11 | import org.elasticsearch.search.aggregations.AggregatorReducer; 12 | import org.elasticsearch.search.aggregations.InternalAggregation; 13 | import org.elasticsearch.search.aggregations.InternalAggregations; 14 | import org.elasticsearch.search.aggregations.InternalMultiBucketAggregation; 15 | import org.elasticsearch.search.aggregations.KeyComparable; 16 | import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation; 17 | import org.elasticsearch.xcontent.ToXContentFragment; 18 | import org.elasticsearch.xcontent.XContentBuilder; 19 | import org.locationtech.jts.io.ParseException; 20 | import org.locationtech.jts.io.geojson.GeoJsonWriter; 21 | import org.opendatasoft.elasticsearch.plugin.GeoUtils; 22 | import org.opendatasoft.elasticsearch.plugin.GeoUtils.OutputFormat; 23 | 24 | import java.io.IOException; 25 | import java.util.ArrayList; 26 | import java.util.Arrays; 27 | import java.util.List; 28 | import java.util.Map; 29 | import java.util.Objects; 30 | 31 | /** 32 | * An internal implementation of {@link InternalMultiBucketAggregation} which extends {@link Aggregation}. 33 | */ 34 | public class InternalGeoShape extends InternalMultiBucketAggregation 35 | implements 36 | GeoShape { 37 | 38 | /** 39 | * The bucket class of InternalGeoShape. 40 | * @see MultiBucketsAggregation.Bucket 41 | */ 42 | public static class InternalBucket extends InternalMultiBucketAggregation.InternalBucket 43 | implements 44 | Writeable, 45 | ToXContentFragment, 46 | GeoShape.Bucket, 47 | KeyComparable { 48 | 49 | protected BytesRef wkb; 50 | protected String wkbHash; 51 | protected String realType; 52 | protected double perimeter; 53 | long bucketOrd; 54 | protected long docCount; 55 | protected InternalAggregations subAggregations; 56 | 57 | public InternalBucket( 58 | BytesRef wkb, 59 | String wkbHash, 60 | String realType, 61 | double perimeter, 62 | long docCount, 63 | InternalAggregations subAggregations 64 | ) { 65 | this.wkb = wkb; 66 | this.wkbHash = wkbHash; 67 | this.realType = realType; 68 | this.docCount = docCount; 69 | this.subAggregations = subAggregations; 70 | this.perimeter = perimeter; 71 | } 72 | 73 | /** 74 | * Read from a stream. 75 | */ 76 | public InternalBucket(StreamInput in) throws IOException { 77 | wkb = in.readBytesRef(); 78 | wkbHash = in.readString(); 79 | realType = in.readString(); 80 | perimeter = in.readDouble(); 81 | docCount = in.readLong(); 82 | subAggregations = InternalAggregations.readFrom(in); 83 | } 84 | 85 | /** 86 | * Write to a stream. 87 | */ 88 | @Override 89 | public void writeTo(StreamOutput out) throws IOException { 90 | out.writeBytesRef(wkb); 91 | out.writeString(wkbHash); 92 | out.writeString(realType); 93 | out.writeDouble(perimeter); 94 | out.writeLong(docCount); 95 | subAggregations.writeTo(out); 96 | } 97 | 98 | @Override 99 | public String getKey() { 100 | return wkb.toString(); 101 | } 102 | 103 | @Override 104 | public String getKeyAsString() { 105 | return wkb.utf8ToString(); 106 | } 107 | 108 | @Override 109 | public int compareKey(InternalGeoShape.InternalBucket other) { 110 | return wkb.compareTo(other.wkb); 111 | } 112 | 113 | private long getShapeHash() { 114 | return wkb.hashCode(); 115 | } 116 | 117 | private String getType() { 118 | return realType; 119 | } 120 | 121 | private int compareTo(InternalBucket other) { 122 | if (this.docCount > other.docCount) { 123 | return 1; 124 | } else if (this.docCount < other.docCount) { 125 | return -1; 126 | } else return 0; 127 | } 128 | 129 | @Override 130 | public long getDocCount() { 131 | return docCount; 132 | } 133 | 134 | @Override 135 | public InternalAggregations getAggregations() { 136 | return subAggregations; 137 | } 138 | 139 | @Override 140 | public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { 141 | builder.startObject(); 142 | builder.field(CommonFields.DOC_COUNT.getPreferredName(), docCount); 143 | subAggregations.toXContentInternal(builder, params); 144 | builder.endObject(); 145 | return builder; 146 | } 147 | 148 | } 149 | 150 | private List buckets; 151 | private final int requiredSize; 152 | private final int shardSize; 153 | private OutputFormat output_format; 154 | private GeoJsonWriter geoJsonWriter; 155 | 156 | public InternalGeoShape( 157 | String name, 158 | List buckets, 159 | OutputFormat output_format, 160 | int requiredSize, 161 | int shardSize, 162 | Map metadata 163 | ) { 164 | super(name, metadata); 165 | this.buckets = buckets; 166 | this.output_format = output_format; 167 | this.requiredSize = requiredSize; 168 | this.shardSize = shardSize; 169 | geoJsonWriter = new GeoJsonWriter(); 170 | } 171 | 172 | /** 173 | * Read from a stream. 174 | */ 175 | public InternalGeoShape(StreamInput in) throws IOException { 176 | super(in); 177 | output_format = OutputFormat.valueOf(in.readString()); 178 | requiredSize = readSize(in); 179 | shardSize = readSize(in); 180 | this.buckets = in.readCollectionAsList(InternalBucket::new); 181 | } 182 | 183 | /** 184 | * Write to a stream. 185 | */ 186 | @Override 187 | protected void doWriteTo(StreamOutput out) throws IOException { 188 | out.writeString(output_format.name()); 189 | writeSize(requiredSize, out); 190 | writeSize(shardSize, out); 191 | out.writeCollection(buckets); 192 | } 193 | 194 | @Override 195 | public String getWriteableName() { 196 | return GeoShapeBuilder.NAME; 197 | } 198 | 199 | @Override 200 | public InternalGeoShape create(List buckets) { 201 | return new InternalGeoShape(this.name, buckets, output_format, requiredSize, shardSize, this.metadata); 202 | } 203 | 204 | @Override 205 | public InternalBucket createBucket(InternalAggregations aggregations, InternalBucket prototype) { 206 | return new InternalBucket( 207 | prototype.wkb, 208 | prototype.wkbHash, 209 | prototype.realType, 210 | prototype.perimeter, 211 | prototype.docCount, 212 | aggregations 213 | ); 214 | } 215 | 216 | @Override 217 | public List getBuckets() { 218 | return buckets; 219 | } 220 | 221 | @Override 222 | protected AggregatorReducer getLeaderReducer(AggregationReduceContext reduceContext, int size) { 223 | return new AggregatorReducer() { 224 | private LongObjectPagedHashMap> buckets = new LongObjectPagedHashMap<>(size, reduceContext.bigArrays()); 225 | 226 | @Override 227 | public void accept(InternalAggregation aggregation) { 228 | InternalGeoShape shape = (InternalGeoShape) aggregation; 229 | 230 | if (buckets == null) { 231 | buckets = new LongObjectPagedHashMap<>(shape.buckets.size(), reduceContext.bigArrays()); 232 | } 233 | 234 | for (InternalBucket bucket : shape.buckets) { 235 | List existingBuckets = buckets.get(bucket.getShapeHash()); 236 | if (existingBuckets == null) { 237 | existingBuckets = new ArrayList<>(); 238 | buckets.put(bucket.getShapeHash(), existingBuckets); 239 | } 240 | existingBuckets.add(bucket); 241 | } 242 | } 243 | 244 | @Override 245 | public InternalAggregation get() { 246 | final int size = !reduceContext.isFinalReduce() ? (int) buckets.size() : Math.min(requiredSize, (int) buckets.size()); 247 | 248 | BucketPriorityQueue ordered = new BucketPriorityQueue(size); 249 | for (LongObjectPagedHashMap.Cursor> cursor : buckets) { 250 | List sameCellBuckets = cursor.value; 251 | ordered.insertWithOverflow(reduceBucket(sameCellBuckets, reduceContext)); 252 | } 253 | buckets.close(); 254 | InternalBucket[] list = new InternalBucket[ordered.size()]; 255 | for (int i = ordered.size() - 1; i >= 0; i--) { 256 | list[i] = ordered.pop(); 257 | } 258 | 259 | return new InternalGeoShape(getName(), Arrays.asList(list), output_format, requiredSize, shardSize, getMetadata()); 260 | } 261 | }; 262 | } 263 | 264 | public InternalBucket reduceBucket(List buckets, AggregationReduceContext context) { 265 | List aggregationsList = new ArrayList<>(buckets.size()); 266 | InternalBucket reduced = null; 267 | for (InternalBucket bucket : buckets) { 268 | if (reduced == null) { 269 | reduced = bucket; 270 | } else { 271 | reduced.docCount += bucket.docCount; 272 | } 273 | aggregationsList.add(bucket.subAggregations); 274 | } 275 | reduced.subAggregations = InternalAggregations.reduce(aggregationsList, context); 276 | return reduced; 277 | } 278 | 279 | @Override 280 | public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException { 281 | builder.startArray(CommonFields.BUCKETS.getPreferredName()); 282 | for (InternalBucket bucket : buckets) { 283 | builder.startObject(); 284 | try { 285 | builder.field(CommonFields.KEY.getPreferredName(), GeoUtils.exportWkbTo(bucket.wkb, output_format, geoJsonWriter)); 286 | builder.field("digest", bucket.wkbHash); 287 | builder.field("type", bucket.getType()); 288 | } catch (ParseException e) { 289 | continue; 290 | } 291 | builder.field(CommonFields.DOC_COUNT.getPreferredName(), bucket.getDocCount()); 292 | bucket.getAggregations().toXContentInternal(builder, params); 293 | builder.endObject(); 294 | } 295 | builder.endArray(); 296 | return builder; 297 | } 298 | 299 | @Override 300 | public int hashCode() { 301 | return Objects.hash(super.hashCode(), buckets, output_format, requiredSize, shardSize); 302 | } 303 | 304 | @Override 305 | public boolean equals(Object obj) { 306 | if (this == obj) return true; 307 | if (obj == null || getClass() != obj.getClass()) return false; 308 | if (!super.equals(obj)) return false; 309 | 310 | InternalGeoShape that = (InternalGeoShape) obj; 311 | return Objects.equals(buckets, that.buckets) 312 | && Objects.equals(output_format, that.output_format) 313 | && Objects.equals(requiredSize, that.requiredSize) 314 | && Objects.equals(shardSize, that.shardSize); 315 | } 316 | 317 | // The priority queue is used to retain the top N buckets (i.e. shapes) 318 | // Buckets are here ordered by area (!) then by hash 319 | static class BucketPriorityQueue extends PriorityQueue { 320 | 321 | BucketPriorityQueue(int size) { 322 | super(size); 323 | } 324 | 325 | @Override 326 | protected boolean lessThan(InternalBucket o1, InternalBucket o2) { 327 | 328 | double i = o2.perimeter - o1.perimeter; 329 | if (i == 0) { 330 | i = o2.compareTo(o1); 331 | if (i == 0) { 332 | i = System.identityHashCode(o2) - System.identityHashCode(o1); 333 | } 334 | } 335 | return i > 0; 336 | } 337 | } 338 | } 339 | -------------------------------------------------------------------------------- /src/main/java/org/opendatasoft/elasticsearch/search/aggregations/bucket/geoshape/GeoShapeAggregator.java: -------------------------------------------------------------------------------- 1 | package org.opendatasoft.elasticsearch.search.aggregations.bucket.geoshape; 2 | 3 | import org.apache.lucene.index.LeafReaderContext; 4 | import org.apache.lucene.util.BytesRef; 5 | import org.apache.lucene.util.BytesRefBuilder; 6 | import org.elasticsearch.ElasticsearchException; 7 | import org.elasticsearch.common.io.stream.StreamInput; 8 | import org.elasticsearch.common.io.stream.StreamOutput; 9 | import org.elasticsearch.common.io.stream.Writeable; 10 | import org.elasticsearch.common.util.BytesRefHash; 11 | import org.elasticsearch.common.util.LongArray; 12 | import org.elasticsearch.common.util.ObjectArray; 13 | import org.elasticsearch.core.Releasables; 14 | import org.elasticsearch.index.fielddata.SortedBinaryDocValues; 15 | import org.elasticsearch.search.aggregations.AggregationExecutionContext; 16 | import org.elasticsearch.search.aggregations.Aggregator; 17 | import org.elasticsearch.search.aggregations.AggregatorFactories; 18 | import org.elasticsearch.search.aggregations.CardinalityUpperBound; 19 | import org.elasticsearch.search.aggregations.InternalAggregation; 20 | import org.elasticsearch.search.aggregations.LeafBucketCollector; 21 | import org.elasticsearch.search.aggregations.LeafBucketCollectorBase; 22 | import org.elasticsearch.search.aggregations.bucket.BucketsAggregator; 23 | import org.elasticsearch.search.aggregations.support.AggregationContext; 24 | import org.elasticsearch.search.aggregations.support.ValuesSource; 25 | import org.elasticsearch.xcontent.ToXContentFragment; 26 | import org.elasticsearch.xcontent.XContentBuilder; 27 | import org.locationtech.jts.geom.Geometry; 28 | import org.locationtech.jts.geom.GeometryFactory; 29 | import org.locationtech.jts.io.ParseException; 30 | import org.locationtech.jts.io.WKBReader; 31 | import org.locationtech.jts.io.WKBWriter; 32 | import org.locationtech.jts.simplify.DouglasPeuckerSimplifier; 33 | import org.locationtech.jts.simplify.TopologyPreservingSimplifier; 34 | import org.opendatasoft.elasticsearch.plugin.GeoUtils; 35 | 36 | import java.io.IOException; 37 | import java.util.Arrays; 38 | import java.util.Map; 39 | import java.util.Objects; 40 | 41 | public class GeoShapeAggregator extends BucketsAggregator { 42 | private final ValuesSource valuesSource; 43 | private final BytesRefHash bucketOrds; 44 | private final BucketCountThresholds bucketCountThresholds; 45 | private GeoUtils.OutputFormat output_format; 46 | private boolean must_simplify; 47 | private int zoom; 48 | private GeoShape.Algorithm algorithm; 49 | 50 | private WKBReader wkbReader; 51 | private final GeometryFactory geometryFactory; 52 | 53 | public GeoShapeAggregator( 54 | String name, 55 | AggregatorFactories factories, 56 | AggregationContext context, 57 | ValuesSource valuesSource, 58 | GeoUtils.OutputFormat output_format, 59 | boolean must_simplify, 60 | int zoom, 61 | GeoShape.Algorithm algorithm, 62 | BucketCountThresholds bucketCountThresholds, 63 | Aggregator parent, 64 | CardinalityUpperBound cardinalityUpperBound, 65 | Map metaData 66 | ) throws IOException { 67 | super(name, factories, context, parent, cardinalityUpperBound, metaData); 68 | this.valuesSource = valuesSource; 69 | this.output_format = output_format; 70 | this.must_simplify = must_simplify; 71 | this.zoom = zoom; 72 | this.algorithm = algorithm; 73 | bucketOrds = new BytesRefHash(1, context.bigArrays()); 74 | this.bucketCountThresholds = bucketCountThresholds; 75 | 76 | this.wkbReader = new WKBReader(); 77 | this.geometryFactory = new GeometryFactory(); 78 | } 79 | 80 | /** 81 | * The collector collects the docs, including or not some score (depending of the including of a Scorer) in the 82 | * collect() process. 83 | * 84 | * The LeafBucketCollector is a "Per-leaf bucket collector". It collects docs for the account of buckets. 85 | */ 86 | @Override 87 | public LeafBucketCollector getLeafCollector(AggregationExecutionContext aggCtx, LeafBucketCollector sub) throws IOException { 88 | if (valuesSource == null) { 89 | return LeafBucketCollector.NO_OP_COLLECTOR; 90 | } 91 | final SortedBinaryDocValues values = valuesSource.bytesValues(aggCtx.getLeafReaderContext()); 92 | return new LeafBucketCollectorBase(sub, values) { 93 | final BytesRefBuilder previous = new BytesRefBuilder(); 94 | 95 | /** 96 | * Collect the given doc in the given bucket. 97 | * Called once for every document matching a query, with the unbased document number. 98 | */ 99 | @Override 100 | public void collect(int doc, long owningBucketOrdinal) throws IOException { 101 | assert owningBucketOrdinal == 0; 102 | if (values.advanceExact(doc)) { 103 | final int valuesCount = values.docValueCount(); 104 | previous.clear(); 105 | 106 | for (int i = 0; i < valuesCount; ++i) { 107 | final BytesRef bytesValue = values.nextValue(); 108 | if (previous.get().equals(bytesValue)) { 109 | continue; 110 | } 111 | long bucketOrdinal = bucketOrds.add(bytesValue); 112 | if (bucketOrdinal < 0) { // already seen 113 | bucketOrdinal = -1 - bucketOrdinal; 114 | collectExistingBucket(sub, doc, bucketOrdinal); 115 | } else { 116 | collectBucket(sub, doc, bucketOrdinal); 117 | } 118 | previous.copyBytes(bytesValue); 119 | } 120 | } 121 | } 122 | }; 123 | } 124 | 125 | @Override 126 | public InternalAggregation[] buildAggregations(LongArray owningBucketOrdinals) throws IOException { 127 | // TODO: replace by calling buildAggregationsForVariableBuckets or buildAggregationsForFixedBucketCount?? 128 | try (ObjectArray topBucketsPerOrd = bigArrays().newObjectArray(owningBucketOrdinals.size())) { 129 | // InternalGeoShape[] results = new InternalGeoShape[owningBucketOrdinals.size()]; 130 | InternalGeoShape[] results = new InternalGeoShape[Math.toIntExact(owningBucketOrdinals.size())]; 131 | 132 | for (long ordIdx = 0; ordIdx < owningBucketOrdinals.size(); ordIdx++) { 133 | assert owningBucketOrdinals.get(ordIdx) == 0; 134 | 135 | final int size = (int) Math.min(bucketOrds.size(), bucketCountThresholds.getShardSize()); 136 | // We will insert buckets in a priority queue with a capacity of up to N=size elements 137 | InternalGeoShape.BucketPriorityQueue ordered = new InternalGeoShape.BucketPriorityQueue(size); 138 | 139 | InternalGeoShape.InternalBucket spare = null; 140 | for (int i = 0; i < bucketOrds.size(); i++) { 141 | if (spare == null) { 142 | spare = new InternalGeoShape.InternalBucket(new BytesRef(), null, null, 0, 0, null); 143 | } 144 | bucketOrds.get(i, spare.wkb); 145 | 146 | // FIXME: why do we need a deepCopy here ? 147 | spare.wkb = BytesRef.deepCopyOf(spare.wkb); 148 | spare.wkbHash = String.valueOf(GeoUtils.getHashFromWKB(spare.wkb)); 149 | 150 | if (GeoUtils.wkbIsPoint(spare.wkb.bytes)) { 151 | spare.perimeter = 0; 152 | spare.realType = "Point"; 153 | } else { 154 | Geometry geom; 155 | 156 | try { 157 | geom = wkbReader.read(spare.wkb.bytes); 158 | } catch (ParseException e) { 159 | continue; 160 | } 161 | 162 | spare.perimeter = geom.getLength(); 163 | spare.realType = geom.getGeometryType(); 164 | 165 | } 166 | 167 | spare.docCount = bucketDocCount(i); 168 | spare.bucketOrd = i; 169 | spare = ordered.insertWithOverflow(spare); 170 | } 171 | 172 | // Once we get the top N results, we can compute a simplification 173 | topBucketsPerOrd.set(ordIdx, new InternalGeoShape.InternalBucket[ordered.size()]); 174 | for (int i = ordered.size() - 1; i >= 0; --i) { 175 | final InternalGeoShape.InternalBucket bucket = ordered.pop(); 176 | 177 | Geometry geom; 178 | try { 179 | geom = wkbReader.read(bucket.wkb.bytes); 180 | } catch (ParseException e) { 181 | continue; 182 | } 183 | if (must_simplify) { 184 | geom = simplifyGeoShape(geom); 185 | bucket.wkb = new BytesRef(new WKBWriter().write(geom)); 186 | bucket.perimeter = geom.getLength(); 187 | 188 | } 189 | 190 | topBucketsPerOrd.get(ordIdx)[i] = bucket; 191 | } 192 | 193 | results[Math.toIntExact(ordIdx)] = new InternalGeoShape( 194 | name, 195 | Arrays.asList(topBucketsPerOrd.get(ordIdx)), 196 | output_format, 197 | bucketCountThresholds.getRequiredSize(), 198 | bucketCountThresholds.getShardSize(), 199 | metadata() 200 | ); 201 | } 202 | 203 | // Build sub-aggregations 204 | buildSubAggsForAllBuckets(topBucketsPerOrd, b -> b.bucketOrd, (b, aggregations) -> b.subAggregations = aggregations); 205 | return results; 206 | } 207 | } 208 | 209 | @Override 210 | public InternalAggregation buildEmptyAggregation() { 211 | return new InternalGeoShape( 212 | name, 213 | null, 214 | output_format, 215 | bucketCountThresholds.getRequiredSize(), 216 | bucketCountThresholds.getShardSize(), 217 | metadata() 218 | ); 219 | } 220 | 221 | private Geometry simplifyGeoShape(Geometry geom) { 222 | Geometry polygonSimplified = getSimplifiedShape(geom); 223 | if (polygonSimplified.isEmpty()) { 224 | polygonSimplified = this.geometryFactory.createPoint(geom.getCoordinate()); 225 | } 226 | return polygonSimplified; 227 | } 228 | 229 | private Geometry getSimplifiedShape(Geometry geometry) { 230 | double tol = GeoUtils.getToleranceFromZoom(zoom); 231 | 232 | switch (algorithm) { 233 | case TOPOLOGY_PRESERVING: 234 | return TopologyPreservingSimplifier.simplify(geometry, tol); 235 | default: 236 | return DouglasPeuckerSimplifier.simplify(geometry, tol); 237 | } 238 | } 239 | 240 | @Override 241 | protected void doClose() { 242 | Releasables.close(bucketOrds); 243 | } 244 | 245 | public static class BucketCountThresholds implements Writeable, ToXContentFragment { 246 | private int requiredSize; 247 | private int shardSize; 248 | 249 | public BucketCountThresholds(int requiredSize, int shardSize) { 250 | this.requiredSize = requiredSize; 251 | this.shardSize = shardSize; 252 | } 253 | 254 | /** 255 | * Read from a stream. 256 | */ 257 | public BucketCountThresholds(StreamInput in) throws IOException { 258 | requiredSize = in.readInt(); 259 | shardSize = in.readInt(); 260 | } 261 | 262 | @Override 263 | public void writeTo(StreamOutput out) throws IOException { 264 | out.writeInt(requiredSize); 265 | out.writeInt(shardSize); 266 | } 267 | 268 | public BucketCountThresholds(GeoShapeAggregator.BucketCountThresholds bucketCountThresholds) { 269 | this(bucketCountThresholds.requiredSize, bucketCountThresholds.shardSize); 270 | } 271 | 272 | public void ensureValidity() { 273 | // shard_size cannot be smaller than size as we need to at least fetch size entries from every shards in order to return size 274 | if (shardSize < requiredSize) { 275 | setShardSize(requiredSize); 276 | } 277 | 278 | if (requiredSize <= 0 || shardSize <= 0) { 279 | throw new ElasticsearchException("parameters [required_size] and [shard_size] must be >0 in geoshape aggregation."); 280 | } 281 | } 282 | 283 | public int getRequiredSize() { 284 | return requiredSize; 285 | } 286 | 287 | public void setRequiredSize(int requiredSize) { 288 | this.requiredSize = requiredSize; 289 | } 290 | 291 | public int getShardSize() { 292 | return shardSize; 293 | } 294 | 295 | public void setShardSize(int shardSize) { 296 | this.shardSize = shardSize; 297 | } 298 | 299 | @Override 300 | public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { 301 | builder.field(GeoShapeBuilder.SIZE_FIELD.getPreferredName(), requiredSize); 302 | if (shardSize != -1) { 303 | builder.field(GeoShapeBuilder.SHARD_SIZE_FIELD.getPreferredName(), shardSize); 304 | } 305 | return builder; 306 | } 307 | 308 | @Override 309 | public int hashCode() { 310 | return Objects.hash(requiredSize, shardSize); 311 | } 312 | 313 | @Override 314 | public boolean equals(Object obj) { 315 | if (obj == null) { 316 | return false; 317 | } 318 | if (getClass() != obj.getClass()) { 319 | return false; 320 | } 321 | GeoShapeAggregator.BucketCountThresholds other = (GeoShapeAggregator.BucketCountThresholds) obj; 322 | return Objects.equals(requiredSize, other.requiredSize) && Objects.equals(shardSize, other.shardSize); 323 | } 324 | } 325 | 326 | } 327 | -------------------------------------------------------------------------------- /src/main/java/org/opendatasoft/elasticsearch/plugin/GeoUtils.java: -------------------------------------------------------------------------------- 1 | package org.opendatasoft.elasticsearch.plugin; 2 | 3 | import org.apache.lucene.util.BytesRef; 4 | import org.elasticsearch.common.geo.GeoPoint; 5 | import org.elasticsearch.common.geo.Orientation; 6 | import org.elasticsearch.common.hash.MurmurHash3; 7 | import org.elasticsearch.geometry.GeometryCollection; 8 | import org.elasticsearch.geometry.Line; 9 | import org.elasticsearch.geometry.LinearRing; 10 | import org.elasticsearch.geometry.MultiLine; 11 | import org.elasticsearch.geometry.MultiPoint; 12 | import org.elasticsearch.geometry.MultiPolygon; 13 | import org.elasticsearch.geometry.Point; 14 | import org.elasticsearch.geometry.Polygon; 15 | import org.locationtech.jts.geom.Coordinate; 16 | import org.locationtech.jts.geom.Geometry; 17 | import org.locationtech.jts.geom.LineString; 18 | import org.locationtech.jts.io.ParseException; 19 | import org.locationtech.jts.io.WKBReader; 20 | import org.locationtech.jts.io.WKBWriter; 21 | import org.locationtech.jts.io.WKTWriter; 22 | import org.locationtech.jts.io.geojson.GeoJsonWriter; 23 | 24 | import java.util.ArrayList; 25 | import java.util.Arrays; 26 | import java.util.List; 27 | import java.util.Vector; 28 | 29 | public class GeoUtils { 30 | public enum OutputFormat { 31 | WKT, 32 | WKB, 33 | GEOJSON 34 | } 35 | 36 | public enum SimplifyAlgorithm { 37 | DOUGLAS_PEUCKER, 38 | TOPOLOGY_PRESERVING 39 | } 40 | 41 | public static long getHashFromWKB(BytesRef wkb) { 42 | return MurmurHash3.hash128(wkb.bytes, wkb.offset, wkb.length, 0, new MurmurHash3.Hash128()).h1; 43 | } 44 | 45 | public static List getBboxFromCoords(Coordinate[] coords) { 46 | GeoPoint topLeft = new GeoPoint( 47 | org.elasticsearch.common.geo.GeoUtils.normalizeLat(coords[0].y), 48 | org.elasticsearch.common.geo.GeoUtils.normalizeLon(coords[0].x) 49 | ); 50 | GeoPoint bottomRight = new GeoPoint( 51 | org.elasticsearch.common.geo.GeoUtils.normalizeLat(coords[2].y), 52 | org.elasticsearch.common.geo.GeoUtils.normalizeLon(coords[2].x) 53 | ); 54 | return Arrays.asList(topLeft, bottomRight); 55 | } 56 | 57 | public static GeoPoint getCentroidFromGeom(Geometry geom) { 58 | Geometry geom_centroid = geom.getCentroid(); 59 | return new GeoPoint(geom_centroid.getCoordinate().y, geom_centroid.getCoordinate().x); 60 | } 61 | 62 | public static double getArea(org.elasticsearch.geometry.Geometry geom) { 63 | Geometry jtsGeom = convertToJTS(geom); 64 | return jtsGeom.getArea(); 65 | } 66 | 67 | public static GeoPoint getCentroidFromGeom(org.elasticsearch.geometry.Geometry geom) { 68 | Geometry jtsGeom = convertToJTS(geom); 69 | org.locationtech.jts.geom.Point point = jtsGeom.getCentroid(); 70 | return new GeoPoint(point.getY(), point.getX()); 71 | } 72 | 73 | public static Geometry getEnvelope(org.elasticsearch.geometry.Geometry geom) { 74 | Geometry jtsGeom = convertToJTS(geom); 75 | return jtsGeom.getEnvelope(); 76 | } 77 | 78 | /** 79 | * Convert Elasticsearch Geometry → JTS Geometry 80 | */ 81 | public static org.locationtech.jts.geom.Geometry convertToJTS(org.elasticsearch.geometry.Geometry esGeometry) { 82 | org.locationtech.jts.geom.GeometryFactory factory = new org.locationtech.jts.geom.GeometryFactory(); 83 | 84 | return switch (esGeometry.type()) { 85 | case POINT -> { 86 | Point esPoint = (Point) esGeometry; 87 | yield factory.createPoint(new Coordinate(esPoint.getLon(), esPoint.getLat())); 88 | } 89 | case LINESTRING -> { 90 | Line esLine = (Line) esGeometry; 91 | Coordinate[] coords = extractCoordinates(esLine.getLons(), esLine.getLats()); 92 | yield factory.createLineString(coords); 93 | } 94 | case POLYGON -> { 95 | Polygon esPolygon = (Polygon) esGeometry; 96 | yield convertPolygonToJTS(esPolygon, factory); 97 | } 98 | case MULTIPOINT -> { 99 | MultiPoint esMultiPoint = (MultiPoint) esGeometry; 100 | Coordinate[] coordinates = new Coordinate[esMultiPoint.size()]; 101 | int index = 0; 102 | 103 | for (org.elasticsearch.geometry.Geometry geom : esMultiPoint) { 104 | Point point = (Point) geom; 105 | coordinates[index++] = new Coordinate(point.getX(), point.getY()); 106 | } 107 | yield factory.createMultiPointFromCoords(coordinates); 108 | } 109 | case MULTILINESTRING -> { 110 | MultiLine esMultiLine = (MultiLine) esGeometry; 111 | LineString[] lineStrings = new LineString[esMultiLine.size()]; 112 | 113 | int index = 0; 114 | for (org.elasticsearch.geometry.Geometry geom : esMultiLine) { 115 | Line line = (Line) geom; 116 | Coordinate[] coords = extractCoordinates(line.getLons(), line.getLats()); 117 | lineStrings[index++] = factory.createLineString(coords); 118 | } 119 | yield factory.createMultiLineString(lineStrings); 120 | } 121 | case MULTIPOLYGON -> { 122 | MultiPolygon esMultiPolygon = (MultiPolygon) esGeometry; 123 | yield convertMultiPolygonToJTS(esMultiPolygon, factory); 124 | } 125 | case GEOMETRYCOLLECTION -> { 126 | @SuppressWarnings("unchecked") 127 | GeometryCollection esCollection = (GeometryCollection< 128 | org.elasticsearch.geometry.Geometry>) esGeometry; 129 | yield convertGeometryCollectionToJTS(esCollection, factory); 130 | } 131 | default -> throw new IllegalArgumentException("Unsupported geometry type: " + esGeometry.type()); 132 | }; 133 | } 134 | 135 | private static Coordinate[] extractCoordinates(double[] longs, double[] lats) { 136 | Coordinate[] coords = new Coordinate[lats.length]; 137 | for (int i = 0; i < lats.length; i++) { 138 | coords[i] = new Coordinate(longs[i], lats[i]); 139 | } 140 | return coords; 141 | } 142 | 143 | private static org.locationtech.jts.geom.Polygon convertPolygonToJTS( 144 | Polygon esPolygon, 145 | org.locationtech.jts.geom.GeometryFactory factory 146 | ) { 147 | // Anneau extérieur 148 | LinearRing exterior = esPolygon.getPolygon(); 149 | Coordinate[] exteriorCoords = extractCoordinates(exterior.getLons(), exterior.getLats()); 150 | org.locationtech.jts.geom.LinearRing jtsExterior = factory.createLinearRing(exteriorCoords); 151 | 152 | // Trous 153 | org.locationtech.jts.geom.LinearRing[] jtsHoles = new org.locationtech.jts.geom.LinearRing[esPolygon.getNumberOfHoles()]; 154 | for (int i = 0; i < esPolygon.getNumberOfHoles(); i++) { 155 | LinearRing hole = esPolygon.getHole(i); 156 | Coordinate[] holeCoords = extractCoordinates(hole.getLons(), hole.getLats()); 157 | jtsHoles[i] = factory.createLinearRing(holeCoords); 158 | } 159 | 160 | return factory.createPolygon(jtsExterior, jtsHoles); 161 | } 162 | 163 | private static org.locationtech.jts.geom.MultiPolygon convertMultiPolygonToJTS( 164 | MultiPolygon esMultiPolygon, 165 | org.locationtech.jts.geom.GeometryFactory factory 166 | ) { 167 | org.locationtech.jts.geom.Polygon[] jtsPolygons = new org.locationtech.jts.geom.Polygon[esMultiPolygon.size()]; 168 | for (int i = 0; i < esMultiPolygon.size(); i++) { 169 | jtsPolygons[i] = convertPolygonToJTS(esMultiPolygon.get(i), factory); 170 | } 171 | return factory.createMultiPolygon(jtsPolygons); 172 | } 173 | 174 | private static org.locationtech.jts.geom.GeometryCollection convertGeometryCollectionToJTS( 175 | GeometryCollection esCollection, 176 | org.locationtech.jts.geom.GeometryFactory factory 177 | ) { 178 | 179 | org.locationtech.jts.geom.Geometry[] jtsGeometries = new org.locationtech.jts.geom.Geometry[esCollection.size()]; 180 | int i = 0; 181 | for (org.elasticsearch.geometry.Geometry geometry : esCollection) { 182 | jtsGeometries[i++] = convertToJTS(geometry); 183 | } 184 | return factory.createGeometryCollection(jtsGeometries); 185 | } 186 | 187 | // Return true if wkb is a point 188 | // http://en.wikipedia.org/wiki/Well-known_text#Well-known_binary 189 | public static boolean wkbIsPoint(byte[] wkb) { 190 | if (wkb.length < 5) { 191 | return false; 192 | } 193 | 194 | // Big endian or little endian shape representation 195 | if (wkb[0] == 0) { 196 | return wkb[1] == 0 && wkb[2] == 0 && wkb[3] == 0 && wkb[4] == 1; 197 | } else { 198 | return wkb[1] == 1 && wkb[2] == 0 && wkb[3] == 0 && wkb[4] == 0; 199 | } 200 | } 201 | 202 | public static double getMeterByPixel(int zoom, double lat) { 203 | return (org.elasticsearch.common.geo.GeoUtils.EARTH_EQUATOR / 256) * (Math.cos(Math.toRadians(lat)) / Math.pow(2, zoom)); 204 | } 205 | 206 | public static double getDecimalDegreeFromMeter(double meter) { 207 | return meter * 360 / org.elasticsearch.common.geo.GeoUtils.EARTH_EQUATOR; 208 | } 209 | 210 | public static double getDecimalDegreeFromMeter(double meter, double latitude) { 211 | return meter * 360 / (org.elasticsearch.common.geo.GeoUtils.EARTH_EQUATOR * Math.cos(Math.toRadians(latitude))); 212 | } 213 | 214 | public static double getToleranceFromZoom(int zoom) { 215 | /* 216 | This is a simplified formula for 217 | double meterByPixel = GeoUtils.getMeterByPixel(zoom, lat); 218 | double tol = GeoUtils.getDecimalDegreeFromMeter(meterByPixel, lat); 219 | */ 220 | return 360 / (256 * Math.pow(2, zoom)); 221 | } 222 | 223 | public static String exportWkbTo(BytesRef wkb, OutputFormat output_format, GeoJsonWriter geoJsonWriter) throws ParseException { 224 | switch (output_format) { 225 | case WKT: 226 | Geometry geom = new WKBReader().read(wkb.bytes); 227 | return new WKTWriter().write(geom); 228 | case WKB: 229 | return WKBWriter.toHex(wkb.bytes); 230 | default: 231 | Geometry geo = new WKBReader().read(wkb.bytes); 232 | return geoJsonWriter.write(geo); 233 | } 234 | } 235 | 236 | public static String exportGeoTo(Geometry geom, OutputFormat outputFormat, GeoJsonWriter geoJsonWriter) { 237 | switch (outputFormat) { 238 | case WKT: 239 | return new WKTWriter().write(geom); 240 | case WKB: 241 | return WKBWriter.toHex(new WKBWriter().write(geom)); 242 | default: 243 | return geoJsonWriter.write(geom); 244 | } 245 | } 246 | 247 | /** 248 | * Remove the duplicated coordinates from a Line 249 | */ 250 | public static Line removeDuplicateCoordinates(Line line) { 251 | List newX = new ArrayList<>(); 252 | List newY = new ArrayList<>(); 253 | 254 | Point previous = null; 255 | for (int i = 0; i < line.length(); i++) { 256 | Point current = new Point(line.getX(i), line.getY(i)); 257 | if ((previous != null) && (previous.equals(current))) { 258 | continue; 259 | } 260 | newX.add(current.getX()); 261 | newY.add(current.getY()); 262 | previous = current; 263 | } 264 | return new Line(newX.stream().mapToDouble(Double::doubleValue).toArray(), newY.stream().mapToDouble(Double::doubleValue).toArray()); 265 | } 266 | 267 | /** 268 | * Remove the duplicated coordinates from a linear ring. 269 | */ 270 | public static LinearRing removeDuplicateCoordinates(LinearRing ring) { 271 | Line line = removeDuplicateCoordinates((Line) ring); 272 | return new LinearRing(line.getX(), line.getY()); 273 | } 274 | 275 | /** 276 | * Remove the duplicated coordinates from a Polygon 277 | */ 278 | public static Polygon removeDuplicateCoordinates(Polygon polygon) { 279 | // Process the exterior ring 280 | LinearRing exteriorRing = removeDuplicateCoordinates(polygon.getPolygon()); 281 | 282 | // Process each hole if necessary 283 | List processedHoles = new ArrayList<>(); 284 | for (int i = 0; i < polygon.getNumberOfHoles(); i++) { 285 | LinearRing hole = polygon.getHole(i); 286 | LinearRing processedHole = removeDuplicateCoordinates(hole); 287 | processedHoles.add(processedHole); 288 | } 289 | 290 | return new Polygon(exteriorRing, processedHoles); 291 | } 292 | 293 | /** 294 | * Remove duplicated coordinates for each Polygon in a MultiPolygon 295 | */ 296 | public static MultiPolygon removeDuplicateCoordinates(MultiPolygon multiPolygon) { 297 | List polygons = new ArrayList<>(); 298 | 299 | for (int i = 0; i < multiPolygon.size(); i++) { 300 | Polygon polygon = multiPolygon.get(i); 301 | Polygon cleaned = removeDuplicateCoordinates(polygon); 302 | polygons.add(cleaned); 303 | } 304 | 305 | return new MultiPolygon(polygons); 306 | } 307 | 308 | /** 309 | * Process and clean-up a GeometryCollection 310 | */ 311 | public static GeometryCollection removeDuplicateCoordinates( 312 | GeometryCollection collection 313 | ) { 314 | List cleanedGeometries = new ArrayList<>(); 315 | 316 | for (org.elasticsearch.geometry.Geometry geometry : collection) { 317 | org.elasticsearch.geometry.Geometry cleaned = removeDuplicateCoordinates(geometry); 318 | if (cleaned != null) { 319 | cleanedGeometries.add(cleaned); 320 | } 321 | } 322 | 323 | return new GeometryCollection<>(cleanedGeometries); 324 | } 325 | 326 | public static org.elasticsearch.geometry.Geometry removeDuplicateCoordinates(org.elasticsearch.geometry.Geometry geometry) { 327 | return switch (geometry.type()) { 328 | case POINT -> geometry; // Point does not have duplicated coordinates 329 | case LINESTRING -> removeDuplicateCoordinates((Line) geometry); 330 | case POLYGON -> removeDuplicateCoordinates((Polygon) geometry); 331 | case MULTIPOLYGON -> removeDuplicateCoordinates((MultiPolygon) geometry); 332 | case GEOMETRYCOLLECTION -> { 333 | // Safe cast 334 | @SuppressWarnings("unchecked") 335 | GeometryCollection collection = (GeometryCollection< 336 | org.elasticsearch.geometry.Geometry>) geometry; 337 | yield removeDuplicateCoordinates(collection); 338 | } 339 | default -> geometry; 340 | }; 341 | } 342 | } 343 | -------------------------------------------------------------------------------- /src/yamlRestTest/resources/rest-api-spec/test/GeoExtension/20_geo_ingest_processor.yml: -------------------------------------------------------------------------------- 1 | --- 2 | "Test geo extension pipeline and dynamic mapping": 3 | 4 | # Create the pipeline 5 | - do: 6 | ingest.put_pipeline: 7 | id: "geo_extension" 8 | body: > 9 | { 10 | "description": "Add extra geo fields to geo_shape fields.", 11 | "processors": [ 12 | { 13 | "geo_extension": { 14 | "field": "geo_shape_*" 15 | } 16 | } 17 | ] 18 | } 19 | - match: { acknowledged: true } 20 | 21 | - do: 22 | ingest.get_pipeline: 23 | id: "geo_extension" 24 | - match: { geo_extension.description: "Add extra geo fields to geo_shape fields." } 25 | 26 | 27 | # Test geo extension dynamic mapping 28 | - do: 29 | indices.create: 30 | index: test_index 31 | 32 | - do: 33 | indices.put_mapping: 34 | index: test_index 35 | body: 36 | dynamic_templates: [ 37 | { 38 | "geo_shapes": { 39 | "match": "geo_shape_*", 40 | "mapping": { 41 | "properties": { 42 | "shape": {"enabled": false}, 43 | "fixed_shape": {"type": "geo_shape"}, 44 | "hash": {"type": "keyword"}, 45 | "wkb": {"type": "binary", "doc_values": true}, 46 | "type": {"type": "keyword"}, 47 | "area": {"type": "half_float"}, 48 | "bbox": {"type": "geo_point"}, 49 | "centroid": {"type": "geo_point"} 50 | } 51 | } 52 | } 53 | } 54 | ] 55 | 56 | - do: 57 | indices.get_mapping: {} 58 | 59 | - match: {test_index.mappings.dynamic_templates.0.geo_shapes.match: "geo_shape_*"} 60 | 61 | - match: {test_index.mappings.dynamic_templates.0.geo_shapes.mapping.properties.fixed_shape.type: "geo_shape"} 62 | - match: {test_index.mappings.dynamic_templates.0.geo_shapes.mapping.properties.hash.type: "keyword"} 63 | - match: {test_index.mappings.dynamic_templates.0.geo_shapes.mapping.properties.wkb.type: "binary"} 64 | - match: {test_index.mappings.dynamic_templates.0.geo_shapes.mapping.properties.wkb.doc_values: true} 65 | - match: {test_index.mappings.dynamic_templates.0.geo_shapes.mapping.properties.type.type: "keyword"} 66 | - match: {test_index.mappings.dynamic_templates.0.geo_shapes.mapping.properties.area.type: "half_float"} 67 | - match: {test_index.mappings.dynamic_templates.0.geo_shapes.mapping.properties.bbox.type: "geo_point"} 68 | - match: {test_index.mappings.dynamic_templates.0.geo_shapes.mapping.properties.centroid.type: "geo_point"} 69 | 70 | 71 | # Test that mapping is correct after a document POST 72 | - do: 73 | index: 74 | index: test_index 75 | pipeline: "geo_extension" 76 | body: { 77 | "id": 1, 78 | "geo_shape_0": { 79 | "type": "Polygon", 80 | "coordinates": [ 81 | [ 82 | [ 83 | 1.6809082031249998, 84 | 49.05227025601607 85 | ], 86 | [ 87 | 2.021484375, 88 | 48.596592251456705 89 | ], 90 | [ 91 | 2.021484375, 92 | 48.596592251456705 93 | ], 94 | [ 95 | 3.262939453125, 96 | 48.922499263758255 97 | ], 98 | [ 99 | 2.779541015625, 100 | 49.196064000723794 101 | ], 102 | [ 103 | 2.0654296875, 104 | 49.23194729854559 105 | ], 106 | [ 107 | 1.6809082031249998, 108 | 49.05227025601607 109 | ] 110 | ] 111 | ] 112 | } 113 | } 114 | 115 | - do: 116 | indices.refresh: {} 117 | 118 | - do: 119 | indices.get_mapping: {} 120 | 121 | - match: {test_index.mappings.properties.geo_shape_0.properties.fixed_shape.type: "geo_shape"} 122 | - match: {test_index.mappings.properties.geo_shape_0.properties.hash.type: "keyword"} 123 | - match: {test_index.mappings.properties.geo_shape_0.properties.wkb.type: "binary"} 124 | - match: {test_index.mappings.properties.geo_shape_0.properties.wkb.doc_values: true} 125 | - match: {test_index.mappings.properties.geo_shape_0.properties.type.type: "keyword"} 126 | - match: {test_index.mappings.properties.geo_shape_0.properties.area.type: "half_float"} 127 | - match: {test_index.mappings.properties.geo_shape_0.properties.bbox.type: "geo_point"} 128 | - match: {test_index.mappings.properties.geo_shape_0.properties.centroid.type: "geo_point"} 129 | 130 | 131 | # Test that the shape has been fixed 132 | - do: 133 | search: 134 | body: 135 | query: 136 | term: 137 | id: 1 138 | 139 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "POLYGON ((2.021484375 48.596592251456705, 3.262939453125 48.922499263758255, 2.779541015625 49.196064000723794, 2.0654296875 49.23194729854559, 1.6809082031249998 49.05227025601607, 2.021484375 48.596592251456705))" } 140 | 141 | # Test the shape type 142 | - match: {hits.hits.0._source.geo_shape_0.type: "Polygon"} 143 | 144 | # Test Point 145 | - do: 146 | index: 147 | index: test_index 148 | pipeline: "geo_extension" 149 | body: { 150 | "id": 2, 151 | "geo_shape_0": { 152 | "type": "Point", 153 | "coordinates": [ 154 | 110.74218749999999, 155 | -82.16644600847728 156 | ] 157 | } 158 | } 159 | 160 | - do: 161 | indices.refresh: {} 162 | 163 | - do: 164 | search: 165 | body: 166 | query: 167 | term: 168 | id: 2 169 | 170 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "POINT (110.74218749999999 -82.16644600847728)"} 171 | - match: {hits.hits.0._source.geo_shape_0.bbox.0.lat: -82.16644600847728} 172 | - match: {hits.hits.0._source.geo_shape_0.bbox.0.lon: 110.74218749999999} 173 | - match: {hits.hits.0._source.geo_shape_0.bbox.1.lat: -82.16644600847728} 174 | - match: {hits.hits.0._source.geo_shape_0.bbox.1.lon: 110.74218749999999} 175 | 176 | # Test Linestring 177 | - do: 178 | index: 179 | index: test_index 180 | pipeline: "geo_extension" 181 | body: { 182 | "id": 3, 183 | "geo_shape_0": { 184 | "type": "LineString", 185 | "coordinates": [ 186 | [ 187 | 110.74218749999999, 188 | -82.16644600847728 189 | ], 190 | [ 191 | 132.890625, 192 | -83.71554430601263 193 | ] 194 | ] 195 | } 196 | } 197 | 198 | - do: 199 | indices.refresh: {} 200 | 201 | - do: 202 | search: 203 | body: 204 | query: 205 | term: 206 | id: 3 207 | 208 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "LINESTRING (110.74218749999999 -82.16644600847728, 132.890625 -83.71554430601263)"} 209 | 210 | # Test MultiPoint 211 | - do: 212 | index: 213 | index: test_index 214 | pipeline: "geo_extension" 215 | body: { 216 | "id": 4, 217 | "geo_shape_0": { 218 | "type": "MultiPoint", 219 | "coordinates": [ 220 | [ 221 | 110.74218749999999, 222 | -82.16644600847728 223 | ], 224 | [ 225 | 132.890625, 226 | -83.71554430601263 227 | ] 228 | ] 229 | } 230 | } 231 | 232 | - do: 233 | indices.refresh: {} 234 | 235 | - do: 236 | search: 237 | body: 238 | query: 239 | term: 240 | id: 4 241 | 242 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "MULTIPOINT (110.74218749999999 -82.16644600847728, 132.890625 -83.71554430601263)"} 243 | 244 | # Test MultiLineString 245 | - do: 246 | index: 247 | index: test_index 248 | pipeline: "geo_extension" 249 | body: { 250 | "id": 5, 251 | "geo_shape_0": { 252 | "type": "MultiLineString", 253 | "coordinates": [ 254 | [[ 255 | 110.74218749999999, 256 | -82.16644600847728 257 | ], 258 | [ 259 | 132.890625, 260 | -83.71554430601263 261 | ]], 262 | [[ 263 | 132.890625, 264 | -83.71554430601263 265 | ], 266 | [ 267 | 140, 268 | -83.94227191521858 269 | ]] 270 | ] 271 | } 272 | } 273 | 274 | - do: 275 | indices.refresh: {} 276 | 277 | - do: 278 | search: 279 | body: 280 | query: 281 | term: 282 | id: 5 283 | 284 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "MULTILINESTRING ((110.74218749999999 -82.16644600847728, 132.890625 -83.71554430601263),(132.890625 -83.71554430601263, 140.0 -83.94227191521858))"} 285 | 286 | 287 | # Test MultiPolygon 288 | - do: 289 | index: 290 | index: test_index 291 | pipeline: "geo_extension" 292 | body: { 293 | "id": 6, 294 | "geo_shape_0": { 295 | "type": "MultiPolygon", 296 | "coordinates": [[ 297 | [ 298 | [ 299 | -2.26318359375, 300 | 48.125767833701666 301 | ], 302 | [ 303 | -1.8814086914062498, 304 | 48.156925112380684 305 | ], 306 | [ 307 | -1.9033813476562498, 308 | 48.31060120649363 309 | ], 310 | [ 311 | -2.26318359375, 312 | 48.125767833701666 313 | ] 314 | ] 315 | ],[ 316 | [ 317 | [ 318 | -1.78802490234375, 319 | 48.23930899024907 320 | ], 321 | [ 322 | -1.7660522460937498, 323 | 48.123934463666366 324 | ], 325 | [ 326 | -1.5985107421875, 327 | 48.1789071002632 328 | ], 329 | [ 330 | -1.78802490234375, 331 | 48.23930899024907 332 | ] 333 | ]] 334 | ] 335 | } 336 | } 337 | 338 | - do: 339 | indices.refresh: {} 340 | 341 | - do: 342 | search: 343 | body: 344 | query: 345 | term: 346 | id: 6 347 | 348 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "MULTIPOLYGON (((-1.8814086914062498 48.156925112380684, -1.9033813476562498 48.31060120649363, -2.26318359375 48.125767833701666, -1.8814086914062498 48.156925112380684)),((-1.7660522460937498 48.123934463666366, -1.5985107421875 48.1789071002632, -1.78802490234375 48.23930899024907, -1.7660522460937498 48.123934463666366)))"} 349 | 350 | # Test GeometryCollection 351 | - do: 352 | index: 353 | index: test_index 354 | pipeline: "geo_extension" 355 | body: { 356 | "id": 7, 357 | "geo_shape_0": { 358 | "type": "GeometryCollection", 359 | "geometries": [ 360 | { 361 | "type": "Polygon", 362 | "coordinates": [ 363 | [ 364 | [ 365 | -123.11839233491114, 366 | 49.2402245918293 367 | ], 368 | [ 369 | -123.11875175091907, 370 | 49.24005998018907 371 | ], 372 | [ 373 | -123.11737309548549, 374 | 49.23887966363327 375 | ], 376 | [ 377 | -123.11703513714964, 378 | 49.23902676693859 379 | ], 380 | [ 381 | -123.11839233491114, 382 | 49.2402245918293 383 | ] 384 | ] 385 | ] 386 | },{ 387 | "type": "LineString", 388 | "coordinates": [ 389 | [ 390 | -123.11826024867999, 391 | 49.24043019142397 392 | ], 393 | [ 394 | -123.11673782884, 395 | 49.23906844767802 396 | ] 397 | ] 398 | } 399 | ] 400 | } 401 | } 402 | 403 | - do: 404 | indices.refresh: {} 405 | 406 | - do: 407 | search: 408 | body: 409 | query: 410 | term: 411 | id: 7 412 | 413 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "GEOMETRYCOLLECTION (POLYGON ((-123.11875175091907 49.24005998018907, -123.11737309548549 49.23887966363327, -123.11703513714964 49.23902676693859, -123.11839233491114 49.2402245918293, -123.11875175091907 49.24005998018907)),LINESTRING (-123.11826024867999 49.24043019142397, -123.11673782884 49.23906844767802))"} 414 | 415 | # Test shape accross dateline is warped correctly 416 | - do: 417 | index: 418 | index: test_index 419 | pipeline: "geo_extension" 420 | body: { 421 | "id": 8, 422 | "geo_shape_0": { 423 | "type": "Polygon", 424 | "coordinates": [ 425 | [ 426 | [ 427 | 110.74218749999999, 428 | -82.16644600847728 429 | ], 430 | [ 431 | 132.890625, 432 | -83.71554430601263 433 | ], 434 | [ 435 | 132.890625, 436 | -83.71554430601263 437 | ], 438 | [ 439 | 213.75, 440 | -83.94227191521858 441 | ], 442 | [ 443 | 110.74218749999999, 444 | -82.16644600847728 445 | ] 446 | ] 447 | ] 448 | } 449 | } 450 | 451 | - do: 452 | indices.refresh: {} 453 | 454 | 455 | # Test that the shape has been fixed 456 | - do: 457 | search: 458 | body: 459 | query: 460 | term: 461 | id: 8 462 | 463 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "MULTIPOLYGON (((180.0 -83.84763778268045, 180.0 -83.36043134509174, 110.74218749999999 -82.16644600847728, 132.890625 -83.71554430601263, 180.0 -83.84763778268045)),((-180.0 -83.36043134509174, -180.0 -83.84763778268045, -146.25 -83.94227191521858, -180.0 -83.36043134509174)))" } 464 | 465 | # Test point deduplication (from Helpscout #22513 - vancouver domain) 466 | - do: 467 | index: 468 | index: test_index 469 | pipeline: "geo_extension" 470 | body: { 471 | "id": 9, 472 | "geo_shape_0": { 473 | "type": "Polygon", 474 | "coordinates": [[ 475 | [-123.05572027973177, 49.25832825652564], 476 | [-123.05565987253833, 49.25831694688045], 477 | [-123.05559934281857, 49.25830631249652], 478 | [-123.05551963301089, 49.25830671063574], 479 | [-123.05551521820138, 49.25865914517688], 480 | [-123.05572342764653, 49.25865850523312], 481 | [-123.05572027973177, 49.25832825652564], 482 | [-123.05572027973177, 49.25832825652564] 483 | ]] 484 | } 485 | } 486 | 487 | - do: 488 | indices.refresh: {} 489 | 490 | 491 | # Test that the shape has been fixed 492 | - do: 493 | search: 494 | body: 495 | query: 496 | term: 497 | id: 9 498 | 499 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "POLYGON ((-123.05565987253833 49.25831694688045, -123.05559934281857 49.25830631249652, -123.05551963301089 49.25830671063574, -123.05551521820138 49.25865914517688, -123.05572342764653 49.25865850523312, -123.05572027973177 49.25832825652564, -123.05565987253833 49.25831694688045))" } 500 | 501 | # Test point deduplication (from Helpscout #22451 - basel-stadt - kept in the original coordinate system) 502 | # This generated an assertion error (!) "GeometryCollection unsupported" with JTS Geom and Elastic 7 503 | # but won't raise an error anymore with elasticsearch.common.geo 504 | # Note that the fixed geo shape is valid but will have strange coordinates. 505 | - do: 506 | index: 507 | index: test_index 508 | pipeline: "geo_extension" 509 | body: { 510 | "id": 10, 511 | "geo_shape_0": { 512 | "type": "Polygon", 513 | "coordinates": [[ 514 | [2611313.705, 1267399.002], 515 | [2611313.705, 1267399.002], 516 | [2611313.663, 1267399.0590000001], 517 | [2611264.938, 1267459.53], 518 | [2611264.723, 1267459.858], 519 | [2611264.576, 1267460.222], 520 | [2611264.503, 1267460.607], 521 | [2611264.506, 1267460.999], 522 | [2611264.586, 1267461.383], 523 | [2611264.74, 1267461.744], 524 | [2611264.96, 1267462.068], 525 | [2611265.24, 1267462.342], 526 | [2611265.568, 1267462.557], 527 | [2611265.932, 1267462.704], 528 | [2611266.3170000003, 1267462.777], 529 | [2611266.7090000003, 1267462.774], 530 | [2611267.093, 1267462.6940000001], 531 | [2611267.454, 1267462.54], 532 | [2611267.778, 1267462.32], 533 | [2611268.052, 1267462.04], 534 | [2611316.752, 1267401.601], 535 | [2611316.7970000003, 1267401.55], 536 | [2611316.867, 1267401.454], 537 | [2611316.867, 1267401.454], 538 | [2611316.937, 1267401.358], 539 | [2611317.136, 1267401.02], 540 | [2611317.265, 1267400.6500000001], 541 | [2611317.319, 1267400.262], 542 | [2611317.2970000003, 1267399.871], 543 | [2611317.199, 1267399.491], 544 | [2611317.028, 1267399.138], 545 | [2611316.792, 1267398.825], 546 | [2611316.499, 1267398.564], 547 | [2611316.161, 1267398.365], 548 | [2611315.791, 1267398.236], 549 | [2611315.403, 1267398.182], 550 | [2611315.012, 1267398.204], 551 | [2611314.632, 1267398.3020000001], 552 | [2611314.279, 1267398.473], 553 | [2611313.966, 1267398.709], 554 | [2611313.705, 1267399.002], 555 | [2611313.705, 1267399.002] 556 | ]] 557 | } 558 | } 559 | 560 | - do: 561 | indices.refresh: {} 562 | 563 | - do: 564 | search: 565 | body: 566 | query: 567 | term: 568 | id: 10 569 | 570 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "POLYGON ((-126.0339999999851 -18.709000000031665, -125.72099999990314 -18.472999999998137, -125.36799999978393 -18.30200000014156, -124.98799999989569 -18.203999999910593, -124.59700000006706 -18.182000000029802, -124.20899999979883 -18.236000000033528, -123.83900000015274 -18.364999999990687, -123.50100000016391 -18.56400000001304, -123.20800000010058 -18.824999999953434, -122.97200000006706 -19.13800000003539, -122.80099999997765 -19.49099999992177, -122.70299999974668 -19.87100000004284, -122.68099999986589 -20.262000000104308, -122.73499999986961 -20.6500000001397, -122.8640000000596 -21.020000000018626, -123.06300000008196 -21.35800000000745, -123.13299999991432 -21.453999999910593, -123.20299999974668 -21.550000000046566, -123.24800000013784 -21.601000000024214, -171.94799999985844 -82.04000000003725, -172.22200000006706 -82.32000000006519, -172.5460000000894 -82.54000000003725, -172.90700000012293 -82.69400000013411, -173.2909999997355 -82.77399999997579, -173.68299999972805 -82.77700000000186, -174.0679999999702 -82.7039999999106, -174.4320000000298 -82.5570000000298, -174.75999999977648 -82.34199999994598, -175.04000000003725 -82.0679999999702, -175.25999999977648 -81.74399999994785, -175.41399999987334 -81.38299999991432, -175.49399999994785 -80.99900000006892, -175.49699999997392 -80.60700000007637, -175.42400000011548 -80.22200000006706, -175.27699999976903 -79.85800000000745, -175.06199999991804 -79.53000000002794, -126.33699999982491 -19.059000000124797, -126.2949999999255 -19.002000000094995, -126.0339999999851 -18.709000000031665))" } 571 | 572 | # Test point deduplication (from Helpscout #22451 - basel-stadt) 573 | - do: 574 | index: 575 | index: test_index 576 | pipeline: "geo_extension" 577 | body: { 578 | "id": 101, 579 | "geo_shape_0": { 580 | "type": "Polygon", 581 | "coordinates": [[ 582 | [7.588936981310943, 47.55720863846534], 583 | [7.588936981310943, 47.55720863846534], 584 | [7.588936424737011, 47.55720915182582], 585 | [7.588290582941092, 47.55775384276131], 586 | [7.588287734663826, 47.557756796361765], 587 | [7.588285790758167, 47.557760072575384], 588 | [7.588284830563759, 47.55776353639435], 589 | [7.588284880300491, 47.557767061872795], 590 | [7.588285952876823, 47.55777051408822], 591 | [7.588288008056212, 47.55777375818632], 592 | [7.588290939196003, 47.557776668391696], 593 | [7.58829466625118, 47.55777912788855], 594 | [7.588299029559907, 47.557781055938285], 595 | [7.588303869460291, 47.55778237180224], 596 | [7.588308986507193, 47.55778302177403], 597 | [7.588314194642488, 47.557782988105124], 598 | [7.588319294546984, 47.55778226205775], 599 | [7.588324087002335, 47.55778087086895], 600 | [7.588328386202518, 47.557778886727185], 601 | [7.588332019577427, 47.55777636381657], 602 | [7.58897752987938, 47.55723196088119], 603 | [7.588978126463396, 47.55723150143134], 604 | [7.588979054061008, 47.55723063683655], 605 | [7.588979054061008, 47.55723063683655], 606 | [7.588979981658589, 47.5572297722418], 607 | [7.588982617038069, 47.55722672896098], 608 | [7.588984321579252, 47.5572233990813], 609 | [7.588985029206171, 47.557219908600395], 610 | [7.588984727012668, 47.55721639244084], 611 | [7.588983415353376, 47.55721297651448], 612 | [7.588981134491882, 47.55720980466902], 613 | [7.588977991046303, 47.55720699368544], 614 | [7.588974091609352, 47.55720465135093], 615 | [7.588969595867449, 47.55720286739679], 616 | [7.588964676742427, 47.557201713549794], 617 | [7.58895952036617, 47.557201234538525], 618 | [7.588954326055416, 47.55720143909957], 619 | [7.588949279815451, 47.557202326993135], 620 | [7.588944594147866, 47.55720387096396], 621 | [7.588940441569443, 47.557205998839706], 622 | [7.588936981310943, 47.55720863846534], 623 | [7.588936981310943, 47.55720863846534] 624 | ]] 625 | } 626 | } 627 | - do: 628 | indices.refresh: {} 629 | # Test that the shape has been fixed 630 | - do: 631 | search: 632 | body: 633 | query: 634 | term: 635 | id: 101 636 | 637 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "POLYGON ((7.588940441569443 47.557205998839706, 7.588944594147866 47.55720387096396, 7.588949279815451 47.557202326993135, 7.588954326055416 47.55720143909957, 7.58895952036617 47.557201234538525, 7.588964676742427 47.557201713549794, 7.588969595867449 47.55720286739679, 7.588974091609352 47.55720465135093, 7.588977991046303 47.55720699368544, 7.588981134491882 47.55720980466902, 7.588983415353376 47.55721297651448, 7.588984727012668 47.55721639244084, 7.588985029206171 47.557219908600395, 7.588984321579252 47.5572233990813, 7.588982617038069 47.55722672896098, 7.588979981658589 47.5572297722418, 7.588979054061008 47.55723063683655, 7.588978126463396 47.55723150143134, 7.58897752987938 47.55723196088119, 7.588332019577427 47.55777636381657, 7.588328386202518 47.557778886727185, 7.588324087002335 47.55778087086895, 7.588319294546984 47.55778226205775, 7.588314194642488 47.557782988105124, 7.588308986507193 47.55778302177403, 7.588303869460291 47.55778237180224, 7.588299029559907 47.557781055938285, 7.58829466625118 47.55777912788855, 7.588290939196003 47.557776668391696, 7.588288008056212 47.55777375818632, 7.588285952876823 47.55777051408822, 7.588284880300491 47.557767061872795, 7.588284830563759 47.55776353639435, 7.588285790758167 47.557760072575384, 7.588287734663826 47.557756796361765, 7.588290582941092 47.55775384276131, 7.588936424737011 47.55720915182582, 7.588936981310943 47.55720863846534, 7.588940441569443 47.557205998839706))"} 638 | 639 | # Test point deduplication on linestring 640 | # (points do not need to be deduplicated on linestrings) 641 | - do: 642 | index: 643 | index: test_index 644 | pipeline: "geo_extension" 645 | body: { 646 | "id": 11, 647 | "geo_shape_0": { 648 | "type": "LineString", 649 | "coordinates": [ 650 | [0.0, 0.0], 651 | [0.0, 0.0], 652 | [1.0, 0.0] 653 | ] 654 | } 655 | } 656 | 657 | - do: 658 | indices.refresh: {} 659 | 660 | 661 | # Test that the shape has been fixed 662 | - do: 663 | search: 664 | body: 665 | query: 666 | term: 667 | id: 11 668 | 669 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "LINESTRING (0.0 0.0, 1.0 0.0)" } 670 | 671 | # Test point deduplication on multipolygon 672 | - do: 673 | index: 674 | index: test_index 675 | pipeline: "geo_extension" 676 | body: { 677 | "id": 12, 678 | "geo_shape_0": { 679 | "type": "MultiPolygon", 680 | "coordinates": [[[ 681 | [0.0, 0.0], 682 | [0.0, 0.0], 683 | [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0] 684 | ]]] 685 | } 686 | } 687 | 688 | - do: 689 | indices.refresh: {} 690 | 691 | 692 | # Test that the shape has been fixed 693 | - do: 694 | search: 695 | body: 696 | query: 697 | term: 698 | id: 12 699 | 700 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "POLYGON ((1.0 0.0, 1.0 1.0, 0.0 1.0, 0.0 0.0, 1.0 0.0))" } 701 | 702 | 703 | # Test point deduplication on geometrycollection 704 | - do: 705 | index: 706 | index: test_index 707 | pipeline: "geo_extension" 708 | body: { 709 | "id": 13, 710 | "geo_shape_0": { 711 | "type": "GeometryCollection", 712 | "geometries": [ 713 | { 714 | "type": "Polygon", 715 | "coordinates": [ 716 | [ 717 | [ 718 | 4.921875, 719 | 46.07323062540835 720 | ], 721 | [ 722 | 10.8984375, 723 | 46.31658418182218 724 | ], 725 | [ 726 | 10.8984375, 727 | 46.31658418182218 728 | ], 729 | [ 730 | 8.7890625, 731 | 47.989921667414194 732 | ], 733 | [ 734 | 4.921875, 735 | 46.07323062540835 736 | ] 737 | ] 738 | ] 739 | }, 740 | { 741 | "type": "Point", 742 | "coordinates": [ 743 | 5.09765625, 744 | 47.66538735632654 745 | ] 746 | } 747 | ] 748 | }} 749 | 750 | - do: 751 | indices.refresh: {} 752 | 753 | 754 | # Test that the shape has been fixed 755 | - do: 756 | search: 757 | body: 758 | query: 759 | term: 760 | id: 13 761 | 762 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "GEOMETRYCOLLECTION (POLYGON ((10.8984375 46.31658418182218, 8.7890625 47.989921667414194, 4.921875 46.07323062540835, 10.8984375 46.31658418182218)),POINT (5.09765625 47.66538735632654))" } 763 | 764 | 765 | # Test polygon invalidity check 766 | # This polygon is valid for OGR (at least under a double floating point precision model) 767 | # But is not valid for ES 7 and should be valid with ES 8 768 | - do: 769 | index: 770 | index: test_index 771 | pipeline: "geo_extension" 772 | body: { 773 | "id": 14, 774 | "geo_shape_0": { 775 | "coordinates": [[[-1,0],[-1,1],[1,1],[1,0], 776 | [0.00000000000000004,0],[0.5,0.5], 777 | [-0.5,0.5],[0,0],[-1,0]]], 778 | "type":"Polygon" 779 | } 780 | } 781 | 782 | - do: 783 | indices.refresh: {} 784 | 785 | # Test that the shape has been fixed 786 | - do: 787 | search: 788 | body: 789 | query: 790 | term: 791 | id: 14 792 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "POLYGON ((0.0 0.0, -0.5 0.5, 0.5 0.5, 4.0E-17 0.0, 1.0 0.0, 1.0 1.0, -1.0 1.0, -1.0 0.0, 0.0 0.0))" } 793 | 794 | 795 | # Test geometrycollection of multi 796 | - do: 797 | index: 798 | index: test_index 799 | pipeline: "geo_extension" 800 | body: { 801 | "id": 15, 802 | "geo_shape_0": { 803 | "type": "GeometryCollection", 804 | "geometries": [ 805 | { 806 | "type": "Point", 807 | "coordinates": [4.0, 46.0] 808 | },{ 809 | "type": "MultiPoint", 810 | "coordinates": [ 811 | [ 812 | 4.921875, 813 | 46.07323062540835 814 | ], 815 | [ 816 | 10.8984375, 817 | 46.31658418182218 818 | ] 819 | ] 820 | } 821 | ] 822 | }} 823 | - do: 824 | indices.refresh: {} 825 | 826 | 827 | # Test that the shape has been fixed 828 | - do: 829 | search: 830 | body: 831 | query: 832 | term: 833 | id: 15 834 | 835 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "GEOMETRYCOLLECTION (POINT (4.0 46.0),MULTIPOINT (4.921875 46.07323062540835, 10.8984375 46.31658418182218))" } 836 | 837 | # Test geometrycollection of geometrycollection 838 | - do: 839 | index: 840 | index: test_index 841 | pipeline: "geo_extension" 842 | body: { 843 | "id": 16, 844 | "geo_shape_0": { 845 | "type": "GeometryCollection", 846 | "geometries": [ 847 | { 848 | "type": "Point", 849 | "coordinates": [ 4.0, 46.0 ] 850 | },{ 851 | "type": "GeometryCollection", 852 | "geometries": [ 853 | { 854 | "type": "Point", 855 | "coordinates": [ 3.0, 45.0 ] 856 | }, 857 | { 858 | "type": "MultiPoint", 859 | "coordinates": [ 860 | [ 861 | 4.921875, 862 | 46.07323062540835 863 | ], 864 | [ 865 | 10.8984375, 866 | 46.31658418182218 867 | ] 868 | ] 869 | } 870 | ] 871 | } 872 | ] 873 | } 874 | } 875 | - do: 876 | indices.refresh: {} 877 | 878 | 879 | # Test that the shape has been fixed 880 | - do: 881 | search: 882 | body: 883 | query: 884 | term: 885 | id: 16 886 | 887 | - match: {hits.hits.0._source.geo_shape_0.fixed_shape: "GEOMETRYCOLLECTION (POINT (4.0 46.0),GEOMETRYCOLLECTION (POINT (3.0 45.0),MULTIPOINT (4.921875 46.07323062540835, 10.8984375 46.31658418182218)))" } 888 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------