Compare commits
51 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 06db4fde05 | |||
| c823ce1946 | |||
| 2fa15f772a | |||
| 02b6d54cc9 | |||
| 8bb3474c05 | |||
| 7e904cdbe7 | |||
| e46b4977a4 | |||
| 5de2e0b96e | |||
| c36b878cee | |||
| 2efa79d469 | |||
| 20fde914df | |||
| 988736dd41 | |||
| 346c5cce58 | |||
| a3ebd8be78 | |||
| 3c6d96e49f | |||
| be70a398be | |||
| e3e666fd2e | |||
| cb3d1e11d3 | |||
| 9e17bf3df8 | |||
| f70a7d6414 | |||
| 13a4aa31f6 | |||
| aa4aecacdf | |||
| 85ed8a4891 | |||
| ae66cbd619 | |||
| 98d1f5bf63 | |||
| d9f71027b6 | |||
| 2729fa95a3 | |||
| 1126c65766 | |||
| db21ab06f9 | |||
| 1af298d95a | |||
| 980c6b350d | |||
| 7efd4b3be7 | |||
| d2cc58ccad | |||
| 109dc05d9b | |||
| edde0214a0 | |||
| c8699d93d0 | |||
| c0b26a51f1 | |||
| 3dbb1e73d6 | |||
| e5efd31973 | |||
| 0637927ed4 | |||
| 16dacbb63c | |||
| 12acddb86d | |||
| 8cef50347e | |||
| ea4d3f9f30 | |||
| b9e2b13f21 | |||
| 5549216db0 | |||
| a2cee9defd | |||
| ea0ac3f7bc | |||
| 49cb56ed0c | |||
| e8f9f9f1e3 | |||
| f91c9c443b |
@@ -9,7 +9,8 @@ Make sure that:
|
||||
-->
|
||||
|
||||
- [ ] You have read the [Spring Data contribution guidelines](https://github.com/spring-projects/spring-data-build/blob/master/CONTRIBUTING.adoc).
|
||||
- [ ] **There is a ticket in the bug tracker for the project in our [issue tracker](https://github.com/spring-projects/spring-data-elasticsearch/issues)**. Add the issue number to the _Closes #issue-number_ line below
|
||||
- [ ] **There is a ticket in the bug tracker for the project in our [issue tracker](https://github.
|
||||
com/spring-projects/spring-data-elasticsearch/issues)**. Add the issue number to the _Closes #issue-number_ line below
|
||||
- [ ] You use the code formatters provided [here](https://github.com/spring-projects/spring-data-build/tree/master/etc/ide) and have them applied to your changes. Don’t submit any formatting related changes.
|
||||
- [ ] You submit test cases (unit or integration tests) that back your changes.
|
||||
- [ ] You added yourself as author in the headers of the classes you touched. Amend the date range in the Apache license header if needed. For new types, add the license header (copy from another file and set the current year only).
|
||||
|
||||
@@ -24,5 +24,3 @@ target
|
||||
|
||||
|
||||
/zap.env
|
||||
/localdocker.env
|
||||
.localdocker-env
|
||||
|
||||
+2
-2
@@ -1,3 +1,3 @@
|
||||
#Tue Jun 13 08:54:05 CEST 2023
|
||||
#Fri Jun 03 09:39:36 CEST 2022
|
||||
wrapperUrl=https\://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
|
||||
distributionUrl=https\://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.2/apache-maven-3.9.2-bin.zip
|
||||
distributionUrl=https\://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.5/apache-maven-3.8.5-bin.zip
|
||||
|
||||
+1
-4
@@ -1,9 +1,6 @@
|
||||
= Spring Data contribution guidelines
|
||||
|
||||
You find the contribution guidelines for Spring Data projects https://github.com/spring-projects/spring-data-build/blob/main/CONTRIBUTING.adoc[here].
|
||||
**Please read these carefully!**
|
||||
|
||||
Do not submit a Pull Request before having created an issue and having discussed it. This prevents you from doing work that might be rejected.
|
||||
|
||||
== Running the test locally
|
||||
|
||||
@@ -11,4 +8,4 @@ In order to run the tests locally with `./mvnw test` you need to have docker run
|
||||
|
||||
== Class names of the test classes
|
||||
|
||||
Test classes that do depend on the client have either `ERHLC` (when using the deprecated Elasticsearch `RestHighLevelClient`) or `ELC` (the new `ElasticsearchClient`) in their name.
|
||||
Tset classes that do depend on the client have either `ERHLC` (when using the deprecated Elasticsearch `RestHighLevelClient`) or `ELC` (the new `ElasticsearchClient`) in their name.
|
||||
|
||||
Vendored
+54
-18
@@ -1,7 +1,7 @@
|
||||
def p = [:]
|
||||
node {
|
||||
checkout scm
|
||||
p = readProperties interpolate: true, file: 'ci/pipeline.properties'
|
||||
checkout scm
|
||||
p = readProperties interpolate: true, file: 'ci/pipeline.properties'
|
||||
}
|
||||
|
||||
pipeline {
|
||||
@@ -9,7 +9,7 @@ pipeline {
|
||||
|
||||
triggers {
|
||||
pollSCM 'H/10 * * * *'
|
||||
upstream(upstreamProjects: "spring-data-commons/3.1.x", threshold: hudson.model.Result.SUCCESS)
|
||||
upstream(upstreamProjects: "spring-data-commons/2.7.x", threshold: hudson.model.Result.SUCCESS)
|
||||
}
|
||||
|
||||
options {
|
||||
@@ -32,14 +32,18 @@ pipeline {
|
||||
options { timeout(time: 30, unit: 'MINUTES') }
|
||||
|
||||
environment {
|
||||
DOCKER_HUB = credentials("${p['docker.credentials']}")
|
||||
ARTIFACTORY = credentials("${p['artifactory.credentials']}")
|
||||
}
|
||||
|
||||
steps {
|
||||
script {
|
||||
docker.image(p['docker.java.main.image']).inside(p['docker.java.inside.docker']) {
|
||||
sh 'PROFILE=none ci/verify.sh'
|
||||
sh "ci/clean.sh"
|
||||
docker.withRegistry(p['docker.registry'], p['docker.credentials']) {
|
||||
docker.image(p['docker.java.main.image']).inside(p['docker.java.inside.docker']) {
|
||||
sh "docker login --username ${DOCKER_HUB_USR} --password ${DOCKER_HUB_PSW}"
|
||||
sh 'PROFILE=none ci/verify.sh'
|
||||
sh "ci/clean.sh"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,14 +63,44 @@ pipeline {
|
||||
label 'data'
|
||||
}
|
||||
options { timeout(time: 30, unit: 'MINUTES') }
|
||||
|
||||
environment {
|
||||
DOCKER_HUB = credentials("${p['docker.credentials']}")
|
||||
ARTIFACTORY = credentials("${p['artifactory.credentials']}")
|
||||
}
|
||||
|
||||
steps {
|
||||
script {
|
||||
docker.image(p['docker.java.next.image']).inside(p['docker.java.inside.docker']) {
|
||||
sh 'PROFILE=none ci/verify.sh'
|
||||
sh "ci/clean.sh"
|
||||
docker.withRegistry(p['docker.registry'], p['docker.credentials']) {
|
||||
docker.image(p['docker.java.next.image']).inside(p['docker.java.inside.docker']) {
|
||||
sh "docker login --username ${DOCKER_HUB_USR} --password ${DOCKER_HUB_PSW}"
|
||||
sh 'PROFILE=none ci/verify.sh'
|
||||
sh "ci/clean.sh"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage("test: baseline (LTS)") {
|
||||
agent {
|
||||
label 'data'
|
||||
}
|
||||
options { timeout(time: 30, unit: 'MINUTES') }
|
||||
|
||||
environment {
|
||||
DOCKER_HUB = credentials("${p['docker.credentials']}")
|
||||
ARTIFACTORY = credentials("${p['artifactory.credentials']}")
|
||||
}
|
||||
|
||||
steps {
|
||||
script {
|
||||
docker.withRegistry(p['docker.registry'], p['docker.credentials']) {
|
||||
docker.image(p['docker.java.lts.image']).inside(p['docker.java.inside.docker']) {
|
||||
sh "docker login --username ${DOCKER_HUB_USR} --password ${DOCKER_HUB_PSW}"
|
||||
sh 'PROFILE=none ci/verify.sh'
|
||||
sh "ci/clean.sh"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,15 +127,17 @@ pipeline {
|
||||
|
||||
steps {
|
||||
script {
|
||||
docker.image(p['docker.java.main.image']).inside(p['docker.java.inside.basic']) {
|
||||
sh 'MAVEN_OPTS="-Duser.name=jenkins -Duser.home=/tmp/jenkins-home" ./mvnw -s settings.xml -Pci,artifactory -Dmaven.repo.local=/tmp/jenkins-home/.m2/spring-data-elasticsearch-non-root ' +
|
||||
'-Dartifactory.server=https://repo.spring.io ' +
|
||||
"-Dartifactory.username=${ARTIFACTORY_USR} " +
|
||||
"-Dartifactory.password=${ARTIFACTORY_PSW} " +
|
||||
"-Dartifactory.staging-repository=libs-snapshot-local " +
|
||||
"-Dartifactory.build-name=spring-data-elasticsearch " +
|
||||
"-Dartifactory.build-number=${BUILD_NUMBER} " +
|
||||
'-Dmaven.test.skip=true clean deploy -U -B'
|
||||
docker.withRegistry(p['docker.registry'], p['docker.credentials']) {
|
||||
docker.image(p['docker.java.main.image']).inside(p['docker.java.inside.basic']) {
|
||||
sh 'MAVEN_OPTS="-Duser.name=jenkins -Duser.home=/tmp/jenkins-home" ./mvnw -s settings.xml -Pci,artifactory -Dmaven.repo.local=/tmp/jenkins-home/.m2/spring-data-elasticsearch-non-root ' +
|
||||
'-Dartifactory.server=https://repo.spring.io ' +
|
||||
"-Dartifactory.username=${ARTIFACTORY_USR} " +
|
||||
"-Dartifactory.password=${ARTIFACTORY_PSW} " +
|
||||
"-Dartifactory.staging-repository=libs-snapshot-local " +
|
||||
"-Dartifactory.build-name=spring-data-elasticsearch " +
|
||||
"-Dartifactory.build-number=${BUILD_NUMBER} " +
|
||||
'-Dmaven.test.skip=true clean deploy -U -B'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-8
@@ -1,3 +1,4 @@
|
||||
|
||||
image:https://spring.io/badges/spring-data-elasticsearch/ga.svg[Spring Data Elasticsearch,link=https://projects.spring.io/spring-data-elasticsearch#quick-start] image:https://spring.io/badges/spring-data-elasticsearch/snapshot.svg[Spring Data Elasticsearch,link=https://projects.spring.io/spring-data-elasticsearch#quick-start]
|
||||
|
||||
= Spring Data for Elasticsearch image:https://jenkins.spring.io/buildStatus/icon?job=spring-data-elasticsearch%2Fmain&subject=Build[link=https://jenkins.spring.io/view/SpringData/job/spring-data-elasticsearch/] https://gitter.im/spring-projects/spring-data[image:https://badges.gitter.im/spring-projects/spring-data.svg[Gitter]]
|
||||
@@ -39,7 +40,7 @@ This means that a switch to this client version can only be done with the next m
|
||||
|
||||
=== Elasticsearch 8 cluster
|
||||
|
||||
It should be possible to use the Elasticsearch 7 client to access a cluster running version 8 by setting the appropriate compatibility headers (see the documentation at https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.clients.configuration). but I encountered and heard of cases where the response from the server is not parseable by the client although the headers are set, so use with care.
|
||||
It should be possible to use the Elasticsearch 7 client to access a cluster running version 8 by setting the appropriate aompatibility headers (see the documentation at https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.clients.configuration). but I encountered and heard of cases where the response from the server is not parseable by the client although the headers are set, so use with care.
|
||||
|
||||
== Code of Conduct
|
||||
|
||||
@@ -137,9 +138,9 @@ To use the Release candidate versions of the upcoming major version, use our Mav
|
||||
</dependency>
|
||||
|
||||
<repository>
|
||||
<id>spring-snapshot</id>
|
||||
<id>spring-libs-snapshot</id>
|
||||
<name>Spring Snapshot Repository</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
<url>https://repo.spring.io/libs-milestone</url>
|
||||
</repository>
|
||||
----
|
||||
|
||||
@@ -154,9 +155,9 @@ If you'd rather like the latest snapshots of the upcoming major version, use our
|
||||
</dependency>
|
||||
|
||||
<repository>
|
||||
<id>spring-snapshot</id>
|
||||
<id>spring-libs-snapshot</id>
|
||||
<name>Spring Snapshot Repository</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<url>https://repo.spring.io/libs-snapshot</url>
|
||||
</repository>
|
||||
----
|
||||
|
||||
@@ -169,6 +170,7 @@ We’d love to help!
|
||||
https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/[reference documentation], and https://docs.spring.io/spring-data/elasticsearch/docs/current/api/[Javadocs].
|
||||
* Learn the Spring basics – Spring Data builds on Spring Framework, check the https://spring.io[spring.io] web-site for a wealth of reference documentation.
|
||||
If you are just starting out with Spring, try one of the https://spring.io/guides[guides].
|
||||
* If you are upgrading, check out the https://docs.spring.io/spring-data/elasticsearch/docs/current/changelog.txt[changelog] for "`new and noteworthy`" features.
|
||||
* Ask a question - we monitor https://stackoverflow.com[stackoverflow.com] for questions tagged with https://stackoverflow.com/tags/spring-data[`spring-data-elasticsearch`].
|
||||
You can also chat with the community on https://gitter.im/spring-projects/spring-data[Gitter].
|
||||
* Report bugs with Spring Data for Elasticsearch at https://github.com/spring-projects/spring-data-elasticsearch/issues[https://github.com/spring-projects/spring-data-elasticsearch/issues].
|
||||
@@ -189,9 +191,7 @@ Attach a link to your code or a compressed file containing your code.
|
||||
== Building from Source
|
||||
|
||||
You don’t need to build from source to use Spring Data (binaries in https://repo.spring.io[repo.spring.io]), but if you want to try out the latest and greatest, Spring Data can be easily built with the https://github.com/takari/maven-wrapper[maven wrapper].
|
||||
|
||||
You need JDK 17 or above to build the _main_ branch.
|
||||
For the branches up to and including release 4.4, JDK 8 is required.
|
||||
You also need JDK 1.8.
|
||||
|
||||
[source,bash]
|
||||
----
|
||||
@@ -205,6 +205,7 @@ _Also see link:CONTRIBUTING.adoc[CONTRIBUTING.adoc] if you wish to submit pull r
|
||||
IMPORTANT: When contributing, please make sure an issue exists in https://github.com/spring-projects/spring-data-elasticsearch/issues[issue tracker] and comment on this issue with how you want to address it.
|
||||
By this we not only know that someone is working on an issue, we can also align architectural questions and possible solutions before work is invested . We so can prevent that much work is put into Pull Requests that have little or no chances of being merged.
|
||||
|
||||
|
||||
=== Building reference documentation
|
||||
|
||||
Building the documentation builds also the project without running tests.
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
# Java versions
|
||||
java.main.tag=17.0.6_10-jdk-focal
|
||||
java.next.tag=20-jdk-jammy
|
||||
java.main.tag=8u332-b09-jdk
|
||||
java.next.tag=11.0.15_10-jdk
|
||||
java.lts.tag=17.0.3_7-jdk
|
||||
|
||||
# Docker container images - standard
|
||||
docker.java.main.image=harbor-repo.vmware.com/dockerhub-proxy-cache/library/eclipse-temurin:${java.main.tag}
|
||||
docker.java.next.image=harbor-repo.vmware.com/dockerhub-proxy-cache/library/eclipse-temurin:${java.next.tag}
|
||||
docker.java.lts.image=harbor-repo.vmware.com/dockerhub-proxy-cache/library/eclipse-temurin:${java.lts.tag}
|
||||
|
||||
# Supported versions of MongoDB
|
||||
docker.mongodb.4.4.version=4.4.18
|
||||
docker.mongodb.5.0.version=5.0.14
|
||||
docker.mongodb.6.0.version=6.0.4
|
||||
docker.mongodb.4.0.version=4.0.28
|
||||
docker.mongodb.4.4.version=4.4.12
|
||||
docker.mongodb.5.0.version=5.0.6
|
||||
|
||||
# Supported versions of Redis
|
||||
docker.redis.6.version=6.2.10
|
||||
docker.redis.6.version=6.2.6
|
||||
|
||||
# Supported versions of Cassandra
|
||||
docker.cassandra.3.version=3.11.14
|
||||
docker.cassandra.3.version=3.11.12
|
||||
|
||||
# Docker environment settings
|
||||
docker.java.inside.basic=-v $HOME:/tmp/jenkins-home
|
||||
|
||||
@@ -5,12 +5,12 @@
|
||||
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-elasticsearch</artifactId>
|
||||
<version>5.1.1</version>
|
||||
<version>4.4.4</version>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.data.build</groupId>
|
||||
<artifactId>spring-data-parent</artifactId>
|
||||
<version>3.1.1</version>
|
||||
<version>2.7.4</version>
|
||||
</parent>
|
||||
|
||||
<name>Spring Data Elasticsearch</name>
|
||||
@@ -18,23 +18,15 @@
|
||||
<url>https://github.com/spring-projects/spring-data-elasticsearch</url>
|
||||
|
||||
<properties>
|
||||
<springdata.commons>3.1.1</springdata.commons>
|
||||
|
||||
<!-- version of the RestHighLevelClient -->
|
||||
<elasticsearch-rhlc>7.17.9</elasticsearch-rhlc>
|
||||
<elasticsearch-rhlc>7.17.6</elasticsearch-rhlc>
|
||||
<!-- version of the new ElasticsearchClient -->
|
||||
<elasticsearch-java>8.7.1</elasticsearch-java>
|
||||
|
||||
<log4j>2.18.0</log4j>
|
||||
<!-- netty dependency can be removed once the WebClient code is gone -->
|
||||
<netty>4.1.90.Final</netty>
|
||||
|
||||
<blockhound-junit>1.0.8.RELEASE</blockhound-junit>
|
||||
<hoverfly>0.14.4</hoverfly>
|
||||
<jsonassert>1.5.1</jsonassert>
|
||||
<testcontainers>1.18.0</testcontainers>
|
||||
<wiremock>2.35.0</wiremock>
|
||||
|
||||
<elasticsearch-java>7.17.6</elasticsearch-java>
|
||||
<log4j>2.17.1</log4j>
|
||||
<netty>4.1.65.Final</netty>
|
||||
<springdata.commons>2.7.4</springdata.commons>
|
||||
<testcontainers>1.16.2</testcontainers>
|
||||
<blockhound-junit>1.0.6.RELEASE</blockhound-junit>
|
||||
<java-module-name>spring.data.elasticsearch</java-module-name>
|
||||
|
||||
<!--
|
||||
@@ -44,6 +36,7 @@
|
||||
-->
|
||||
<mvn.unit-test.goal>test</mvn.unit-test.goal>
|
||||
<mvn.integration-test-elasticsearch.goal>integration-test</mvn.integration-test-elasticsearch.goal>
|
||||
<mvn.integration-test-opensearch.goal>none</mvn.integration-test-opensearch.goal>
|
||||
</properties>
|
||||
|
||||
<developers>
|
||||
@@ -144,12 +137,11 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- optional Elasticsearch RestHighLevelClient, deprecated in SDE 5.0 -->
|
||||
<!-- Elasticsearch RestHighLevelClient, will be removed probably in SDE 5 -->
|
||||
<dependency>
|
||||
<groupId>org.elasticsearch.client</groupId>
|
||||
<artifactId>elasticsearch-rest-high-level-client</artifactId>
|
||||
<version>${elasticsearch-rhlc}</version>
|
||||
<optional>true</optional>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>commons-logging</groupId>
|
||||
@@ -193,49 +185,39 @@
|
||||
</dependency>
|
||||
|
||||
<!-- CDI -->
|
||||
|
||||
<!-- Dependency order required to build against CDI 1.0 and test with CDI 2.0 -->
|
||||
<dependency>
|
||||
<groupId>javax.interceptor</groupId>
|
||||
<artifactId>javax.interceptor-api</artifactId>
|
||||
<version>1.2.2</version>
|
||||
<groupId>org.apache.geronimo.specs</groupId>
|
||||
<artifactId>geronimo-jcdi_2.0_spec</artifactId>
|
||||
<version>1.3</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>jakarta.enterprise</groupId>
|
||||
<artifactId>jakarta.enterprise.cdi-api</artifactId>
|
||||
<version>3.0.1</version>
|
||||
<groupId>javax.interceptor</groupId>
|
||||
<artifactId>javax.interceptor-api</artifactId>
|
||||
<version>1.2.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<version>${cdi}</version>
|
||||
<scope>provided</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>jakarta.annotation</groupId>
|
||||
<artifactId>jakarta.annotation-api</artifactId>
|
||||
<version>${jakarta-annotation-api}</version>
|
||||
<groupId>javax.annotation</groupId>
|
||||
<artifactId>javax.annotation-api</artifactId>
|
||||
<version>${javax-annotation-api}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.openwebbeans</groupId>
|
||||
<artifactId>openwebbeans-se</artifactId>
|
||||
<classifier>jakarta</classifier>
|
||||
<version>${webbeans}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.openwebbeans</groupId>
|
||||
<artifactId>openwebbeans-spi</artifactId>
|
||||
<classifier>jakarta</classifier>
|
||||
<version>${webbeans}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.openwebbeans</groupId>
|
||||
<artifactId>openwebbeans-impl</artifactId>
|
||||
<classifier>jakarta</classifier>
|
||||
<version>${webbeans}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
@@ -279,17 +261,35 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!--
|
||||
we don't use lombok in Spring Data Elasticsearch anymore. But the dependency is set in the parent project, and so the
|
||||
lombok compiler stuff is executed regardless of the fact that we don't need it.
|
||||
On AdoptOpenJdk 16.0.0 this leads to an error, so the project does not build.
|
||||
Therefore we replace lombok with a jar - that just contains an empty file - that lives in a local maven repository in
|
||||
src/test/resources/local-maven-repo/
|
||||
It was installed with
|
||||
mvn deploy:deploy-file -DgroupId=org.projectlombok -DartifactId=lombok -Dversion=999999 -Durl=file:./src/test/resources/local-maven-repo/ -DrepositoryId=local-maven-repo -DupdateReleaseInfo=true -Dfile=path/to/empty.jar
|
||||
-->
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<!--suppress MavenPackageUpdate -->
|
||||
<version>999999</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.skyscreamer</groupId>
|
||||
<artifactId>jsonassert</artifactId>
|
||||
<version>${jsonassert}</version>
|
||||
<version>1.5.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.tomakehurst</groupId>
|
||||
<artifactId>wiremock-jre8</artifactId>
|
||||
<version>${wiremock}</version>
|
||||
<version>2.32.0</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<!-- these exclusions are needed because of Elasticsearch JarHell-->
|
||||
@@ -307,7 +307,7 @@
|
||||
<dependency>
|
||||
<groupId>io.specto</groupId>
|
||||
<artifactId>hoverfly-java-junit5</artifactId>
|
||||
<version>${hoverfly}</version>
|
||||
<version>0.14.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
@@ -401,8 +401,42 @@
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</execution>
|
||||
<!-- execution to run the integration tests against Opensearch -->
|
||||
<execution>
|
||||
<id>integration-test-opensearch</id>
|
||||
<phase>${mvn.integration-test-opensearch.goal}</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<groups>integration-test</groups>
|
||||
<systemPropertyVariables>
|
||||
<sde.integration-test.environment>opensearch</sde.integration-test.environment>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.pitest</groupId>
|
||||
<artifactId>pitest-maven</artifactId>
|
||||
<version>1.5.2</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.pitest</groupId>
|
||||
<artifactId>pitest-junit5-plugin</artifactId>
|
||||
<version>0.12</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<configuration>
|
||||
<excludedGroups>integration-test</excludedGroups>
|
||||
<targetClasses>
|
||||
<param>org.springframework.data.elasticsearch.core.geo.*</param>
|
||||
</targetClasses>
|
||||
<excludedMethods>toString</excludedMethods>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
@@ -464,8 +498,23 @@
|
||||
</profiles>
|
||||
|
||||
<repositories>
|
||||
|
||||
|
||||
<repository>
|
||||
<id>spring-libs-release</id>
|
||||
<url>https://repo.spring.io/libs-release</url>
|
||||
</repository>
|
||||
|
||||
<repository>
|
||||
<id>local-maven-repo</id>
|
||||
<url>file:///${project.basedir}/src/test/resources/local-maven-repo</url>
|
||||
</repository>
|
||||
|
||||
</repositories>
|
||||
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>spring-plugins-release</id>
|
||||
<url>https://repo.spring.io/plugins-release</url>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -5,15 +5,13 @@ BioMed Central Development Team; Oliver Drotbohm; Greg Turnquist; Christoph Stro
|
||||
ifdef::backend-epub3[:front-cover-image: image:epub-cover.png[Front Cover,1050,1600]]
|
||||
:spring-data-commons-docs: ../../../../spring-data-commons/src/main/asciidoc
|
||||
|
||||
(C) 2013-2022 The original author(s).
|
||||
(C) 2013-2021 The original author(s).
|
||||
|
||||
NOTE: Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.
|
||||
|
||||
toc::[]
|
||||
|
||||
include::preface.adoc[]
|
||||
include::{spring-data-commons-docs}/upgrade.adoc[leveloffset=+1]
|
||||
|
||||
|
||||
:leveloffset: +1
|
||||
include::{spring-data-commons-docs}/repositories.adoc[]
|
||||
|
||||
@@ -17,9 +17,9 @@ include::reference/elasticsearch-new.adoc[leveloffset=+1]
|
||||
* Version Control - https://github.com/spring-projects/spring-data-elasticsearch
|
||||
* API Documentation - https://docs.spring.io/spring-data/elasticsearch/docs/current/api/
|
||||
* Bugtracker - https://github.com/spring-projects/spring-data-elasticsearch/issues
|
||||
* Release repository - https://repo1.maven.org/maven2/
|
||||
* Milestone repository - https://repo.spring.io/milestone/
|
||||
* Snapshot repository - https://repo.spring.io/snapshot/
|
||||
* Release repository - https://repo.spring.io/libs-release
|
||||
* Milestone repository - https://repo.spring.io/libs-milestone
|
||||
* Snapshot repository - https://repo.spring.io/libs-snapshot
|
||||
|
||||
[[preface.requirements]]
|
||||
== Requirements
|
||||
@@ -37,18 +37,15 @@ built and tested.
|
||||
[cols="^,^,^,^,^",options="header"]
|
||||
|===
|
||||
| Spring Data Release Train | Spring Data Elasticsearch | Elasticsearch | Spring Framework | Spring Boot
|
||||
| 2023.0 (Ullmann) | 5.1.x | 8.7.1 | 6.0.x | 3.1.x
|
||||
| 2022.0 (Turing) | 5.0.x | 8.5.3 | 6.0.x | 3.0.x
|
||||
| 2021.2 (Raj) | 4.4.xfootnote:oom[Out of maintenance] | 7.17.3 | 5.3.x | 2.7.x
|
||||
| 2021.1 (Q) | 4.3.xfootnote:oom[] | 7.15.2 | 5.3.x | 2.6.x
|
||||
| 2021.0 (Pascal) | 4.2.xfootnote:oom[] | 7.12.0 | 5.3.x | 2.5.x
|
||||
| 2020.0 (Ockham) | 4.1.xfootnote:oom[] | 7.9.3 | 5.3.2 | 2.4.x
|
||||
| Neumann | 4.0.xfootnote:oom[] | 7.6.2 | 5.2.12 |2.3.x
|
||||
| Moore | 3.2.xfootnote:oom[] |6.8.12 | 5.2.12| 2.2.x
|
||||
| Lovelace | 3.1.xfootnote:oom[] | 6.2.2 | 5.1.19 |2.1.x
|
||||
| Kay | 3.0.xfootnote:oom[] | 5.5.0 | 5.0.13 | 2.0.x
|
||||
| Ingalls | 2.1.xfootnote:oom[] | 2.4.0 | 4.3.25 | 1.5.x
|
||||
| 2021.2 (Raj) | 4.4.x | 7.17.6 | 5.3.x | 2.7.x
|
||||
| 2021.1 (Q) | 4.3.x | 7.15.2 | 5.3.x | 2.6.x
|
||||
| 2021.0 (Pascal) | 4.2.xfootnote:oom[Out of maintenance] | 7.12.0 | 5.3.x | 2.5.x
|
||||
| 2020.0 (Ockham)footnote:oom[] | 4.1.xfootnote:oom[] | 7.9.3 | 5.3.2 | 2.4.x
|
||||
| Neumannfootnote:oom[] | 4.0.xfootnote:oom[] | 7.6.2 | 5.2.12 |2.3.x
|
||||
| Moorefootnote:oom[] | 3.2.xfootnote:oom[] |6.8.12 | 5.2.12| 2.2.x
|
||||
| Lovelacefootnote:oom[] | 3.1.xfootnote:oom[] | 6.2.2 | 5.1.19 |2.1.x
|
||||
| Kayfootnote:oom[] | 3.0.xfootnote:oom[] | 5.5.0 | 5.0.13 | 2.0.x
|
||||
| Ingallsfootnote:oom[] | 2.1.xfootnote:oom[] | 2.4.0 | 4.3.25 | 1.5.x
|
||||
|===
|
||||
|
||||
Support for upcoming versions of Elasticsearch is being tracked and general compatibility should be given assuming
|
||||
the usage of the <<elasticsearch.operations,ElasticsearchOperations interface>>.
|
||||
Support for upcoming versions of Elasticsearch is being tracked and general compatibility should be given assuming the usage of the <<elasticsearch.clients.rest,high-level REST client>>.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
[[elasticsearch.auditing]]
|
||||
== Elasticsearch Auditing
|
||||
|
||||
[[elasticsearch.auditing.preparing]]
|
||||
=== Preparing entities
|
||||
|
||||
In order for the auditing code to be able to decide whether an entity instance is new, the entity must implement the `Persistable<ID>` interface which is defined as follows:
|
||||
@@ -55,7 +54,6 @@ public class Person implements Persistable<Long> {
|
||||
<.> the getter is the required implementation from the interface
|
||||
<.> an object is new if it either has no `id` or none of fields containing creation attributes are set.
|
||||
|
||||
[[elasticsearch.auditing.activating]]
|
||||
=== Activating auditing
|
||||
|
||||
After the entities have been set up and providing the `AuditorAware` - or `ReactiveAuditorAware` - the Auditing must be activated by setting the `@EnableElasticsearchAuditing` on a configuration class:
|
||||
|
||||
@@ -3,126 +3,18 @@
|
||||
|
||||
This chapter illustrates configuration and usage of supported Elasticsearch client implementations.
|
||||
|
||||
Spring Data Elasticsearch operates upon an Elasticsearch client (provided by Elasticsearch client libraries) that is
|
||||
connected to a single Elasticsearch node or a cluster.
|
||||
Although the Elasticsearch Client can be used directly to work with the cluster, applications using Spring Data
|
||||
Elasticsearch normally use the higher level abstractions of <<elasticsearch.operations>> and <<elasticsearch.repositories>>.
|
||||
Spring Data Elasticsearch operates upon an Elasticsearch client that is connected to a single Elasticsearch node or a cluster.
|
||||
Although the Elasticsearch Client can be used to work with the cluster, applications using Spring Data Elasticsearch normally use the higher level abstractions of <<elasticsearch.operations>> and <<elasticsearch.repositories>>.
|
||||
|
||||
[[elasticsearch.clients.restclient]]
|
||||
== Imperative Rest Client
|
||||
[[elasticsearch.clients.rest]]
|
||||
== High Level REST Client
|
||||
|
||||
To use the imperative (non-reactive) client, a configuration bean must be configured like this:
|
||||
The Java High Level REST Client is the default client of Elasticsearch, it is configured like shown:
|
||||
|
||||
.High Level REST Client
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
import org.springframework.data.elasticsearch.client.elc.ElasticsearchConfiguration;
|
||||
|
||||
@Configuration
|
||||
public class MyClientConfig extends ElasticsearchConfiguration {
|
||||
|
||||
@Override
|
||||
public ClientConfiguration clientConfiguration() {
|
||||
return ClientConfiguration.builder() <.>
|
||||
.connectedTo("localhost:9200")
|
||||
.build();
|
||||
}
|
||||
}
|
||||
----
|
||||
<.> for a detailed description of the builder methods see <<elasticsearch.clients.configuration>>
|
||||
====
|
||||
|
||||
The following beans can then be injected in other Spring components:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@Autowired
|
||||
ElasticsearchOperations operations; <.>
|
||||
|
||||
@Autowired
|
||||
ElasticsearchClient elasticsearchClient; <.>
|
||||
|
||||
@Autowired
|
||||
RestClient restClient; <.>
|
||||
----
|
||||
|
||||
<.> an implementation of `ElasticsearchOperations`
|
||||
<.> the `co.elastic.clients.elasticsearch.ElasticsearchClient` that is used.
|
||||
<.> the low level `RestClient` from the Elasticsearch libraries
|
||||
====
|
||||
|
||||
Basically one should just use the `ElasticsearchOperations` to interact with the Elasticsearch cluster.
|
||||
When using repositories, this instance is used under the hood as well.
|
||||
|
||||
[[elasticsearch.clients.reactiverestclient]]
|
||||
== Reactive Rest Client
|
||||
|
||||
When working with the reactive stack, the configuration must be derived from a different class:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
import org.springframework.data.elasticsearch.client.elc.ReactiveElasticsearchConfiguration;
|
||||
|
||||
@Configuration
|
||||
public class MyClientConfig extends ReactiveElasticsearchConfiguration {
|
||||
|
||||
@Override
|
||||
public ClientConfiguration clientConfiguration() {
|
||||
return ClientConfiguration.builder() <.>
|
||||
.connectedTo("localhost:9200")
|
||||
.build();
|
||||
}
|
||||
}
|
||||
----
|
||||
<.> for a detailed description of the builder methods see <<elasticsearch.clients.configuration>>
|
||||
====
|
||||
|
||||
The following beans can then be injected in other Spring components:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@Autowired
|
||||
ReactiveElasticsearchOperations operations; <.>
|
||||
|
||||
@Autowired
|
||||
ReactiveElasticsearchClient elasticsearchClient; <.>
|
||||
|
||||
@Autowired
|
||||
RestClient restClient; <.>
|
||||
----
|
||||
|
||||
the following can be injected:
|
||||
|
||||
<.> an implementation of `ReactiveElasticsearchOperations`
|
||||
<.> the `org.springframework.data.elasticsearch.client.elc.ReactiveElasticsearchClient` that is used.
|
||||
This is a reactive implementation based on the Elasticsearch client implementation.
|
||||
<.> the low level `RestClient` from the Elasticsearch libraries
|
||||
====
|
||||
|
||||
Basically one should just use the `ReactiveElasticsearchOperations` to interact with the Elasticsearch cluster.
|
||||
When using repositories, this instance is used under the hood as well.
|
||||
|
||||
[[elasticsearch.clients.resthighlevelclient]]
|
||||
== High Level REST Client (deprecated)
|
||||
|
||||
[CAUTION]
|
||||
====
|
||||
The Elasticsearch Java RestHighLevelClient is deprecated, but still can be configured like shown (make sure to read
|
||||
<<elasticsearch-migration-guide-4.4-5.0.old-client>> as well).
|
||||
|
||||
It should only be used to access an Elasticsearch cluster running version 7, even with the compatibility headers set
|
||||
there are cases where the `RestHighLevelClient` cannot read the responses sent from a version 8 cluster.
|
||||
====
|
||||
|
||||
.RestHighLevelClient
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
import org.springframework.data.elasticsearch.client.erhlc.AbstractElasticsearchConfiguration;
|
||||
|
||||
@Configuration
|
||||
public class RestClientConfig extends AbstractElasticsearchConfiguration {
|
||||
|
||||
@@ -144,6 +36,15 @@ public class RestClientConfig extends AbstractElasticsearchConfiguration {
|
||||
RestHighLevelClient highLevelClient;
|
||||
|
||||
RestClient lowLevelClient = highLevelClient.lowLevelClient(); <3>
|
||||
|
||||
// ...
|
||||
|
||||
IndexRequest request = new IndexRequest("spring-data")
|
||||
.id(randomID())
|
||||
.source(singletonMap("feature", "high-level-rest-client"))
|
||||
.setRefreshPolicy(IMMEDIATE);
|
||||
|
||||
IndexResponse response = highLevelClient.index(request,RequestOptions.DEFAULT);
|
||||
----
|
||||
|
||||
<1> Use the builder to provide cluster addresses, set default `HttpHeaders` or enable SSL.
|
||||
@@ -152,25 +53,16 @@ public class RestClientConfig extends AbstractElasticsearchConfiguration {
|
||||
====
|
||||
|
||||
[[elasticsearch.clients.reactive]]
|
||||
== Reactive Client (deprecated)
|
||||
== Reactive Client
|
||||
|
||||
The `org.springframework.data.elasticsearch.client.erhlc.ReactiveElasticsearchClient` is a non official driver based on `WebClient`.
|
||||
The `ReactiveElasticsearchClient` is a non official driver based on `WebClient`.
|
||||
It uses the request/response objects provided by the Elasticsearch core project.
|
||||
Calls are directly operated on the reactive stack, **not** wrapping async (thread pool bound) responses into reactive types.
|
||||
|
||||
[CAUTION]
|
||||
====
|
||||
This was the first reactive implementation Spring Data Elasticsearch provided, but now is deprecated in favour
|
||||
of the `org.springframework.data.elasticsearch.client.elc.ReactiveElasticsearchClient`
|
||||
which uses the functionality offered by the new Elasticsearch client libraries.
|
||||
====
|
||||
|
||||
.Reactive REST Client (deprecated)
|
||||
.Reactive REST Client
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
import org.springframework.data.elasticsearch.client.erhlc.AbstractReactiveElasticsearchConfiguration;
|
||||
|
||||
@Configuration
|
||||
public class ReactiveRestClientConfig extends AbstractReactiveElasticsearchConfiguration {
|
||||
|
||||
@@ -197,6 +89,8 @@ Mono<IndexResponse> response = client.index(request ->
|
||||
<.> Use the builder to provide cluster addresses, set default `HttpHeaders` or enable SSL.
|
||||
====
|
||||
|
||||
NOTE: The ReactiveClient response, especially for search operations, is bound to the `from` (offset) & `size` (limit) options of the request.
|
||||
|
||||
[[elasticsearch.clients.configuration]]
|
||||
== Client Configuration
|
||||
|
||||
@@ -206,11 +100,6 @@ Client behaviour can be changed via the `ClientConfiguration` that allows to set
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
import org.springframework.data.elasticsearch.client.ClientConfiguration;
|
||||
import org.springframework.data.elasticsearch.support.HttpHeaders;
|
||||
|
||||
import static org.springframework.data.elasticsearch.client.elc.ElasticsearchClients.*;
|
||||
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
httpHeaders.add("some-header", "on every request") <.>
|
||||
|
||||
@@ -229,7 +118,12 @@ ClientConfiguration clientConfiguration = ClientConfiguration.builder()
|
||||
return headers;
|
||||
})
|
||||
.withClientConfigurer( <.>
|
||||
ElasticsearchClientConfigurationCallback.from(clientBuilder -> {
|
||||
ReactiveRestClients.WebClientConfigurationCallback.from(webClient -> {
|
||||
// ...
|
||||
return webClient;
|
||||
}))
|
||||
.withClientConfigurer( <.>
|
||||
RestClients.RestClientConfigurationCallback.from(clientBuilder -> {
|
||||
// ...
|
||||
return clientBuilder;
|
||||
}))
|
||||
@@ -240,76 +134,31 @@ ClientConfiguration clientConfiguration = ClientConfiguration.builder()
|
||||
|
||||
<.> Define default headers, if they need to be customized
|
||||
<.> Use the builder to provide cluster addresses, set default `HttpHeaders` or enable SSL.
|
||||
<.> Optionally enable SSL. There exist overloads of this function that can take a `SSLContext` or as an alternative the fingerprint of the certificate as it is output by Elasticsearch 8 on startup.
|
||||
<.> Optionally enable SSL.
|
||||
<.> Optionally set a proxy.
|
||||
<.> Optionally set a path prefix, mostly used when different clusters a behind some reverse proxy.
|
||||
<.> Set the connection timeout.
|
||||
Default is 10 sec.
|
||||
<.> Set the socket timeout.
|
||||
Default is 5 sec.
|
||||
<.> Optionally set headers.
|
||||
<.> Add basic authentication.
|
||||
<.> A `Supplier<HttpHeaders>` function can be specified which is called every time before a request is sent to Elasticsearch - here, as an example, the current time is written in a header.
|
||||
<.> a function to configure the created client (see <<elasticsearch.clients.configuration.callbacks>>), can be added
|
||||
multiple times.
|
||||
<.> A `Supplier<Header>` function can be specified which is called every time before a request is sent to Elasticsearch - here, as an example, the current time is written in a header.
|
||||
<.> for reactive setup a function configuring the `WebClient`
|
||||
<.> for non-reactive setup a function configuring the REST client
|
||||
====
|
||||
|
||||
IMPORTANT: Adding a Header supplier as shown in above example allows to inject headers that may change over the time, like authentication JWT tokens.
|
||||
If this is used in the reactive setup, the supplier function *must not* block!
|
||||
|
||||
[[elasticsearch.clients.configuration.callbacks]]
|
||||
=== Client configuration callbacks
|
||||
|
||||
The `ClientConfiguration` class offers the most common parameters to configure the client. In the case this is not
|
||||
enough, the user can add callback functions by using the `withClientConfigurer(ClientConfigurationCallback<?>)` method.
|
||||
|
||||
The following callbacks are provided:
|
||||
|
||||
[[elasticsearch.clients.configuration.callbacks.rest]]
|
||||
==== Configuration of the low level Elasticsearch `RestClient`:
|
||||
|
||||
This callback provides a `org.elasticsearch.client.RestClientBuilder` that can be used to configure the Elasticsearch
|
||||
`RestClient`:
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
ClientConfiguration.builder()
|
||||
.withClientConfigurer(ElasticsearchClients.ElasticsearchRestClientConfigurationCallback.from(restClientBuilder -> {
|
||||
// configure the Elasticsearch RestClient
|
||||
return restClientBuilder;
|
||||
}))
|
||||
.build();
|
||||
----
|
||||
====
|
||||
|
||||
[[elasticsearch.clients.configurationcallbacks.httpasync]]
|
||||
==== Configuration of the HttpAsyncClient used by the low level Elasticsearch `RestClient`:
|
||||
|
||||
This callback provides a `org.apache.http.impl.nio.client.HttpAsyncClientBuilder` to configure the HttpCLient that is
|
||||
used by the `RestClient`.
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
ClientConfiguration.builder()
|
||||
.withClientConfigurer(ElasticsearchClients.ElasticsearchHttpClientConfigurationCallback.from(httpAsyncClientBuilder -> {
|
||||
// configure the HttpAsyncClient
|
||||
return httpAsyncClientBuilder;
|
||||
}))
|
||||
.build();
|
||||
----
|
||||
====
|
||||
|
||||
[[elasticsearch.clients.configuration.headers]]
|
||||
=== Elasticsearch 7 compatibility headers
|
||||
|
||||
When using the deprecated `RestHighLevelClient` and accessing an Elasticsearch cluster that is running on version 8, it is necessary to set the compatibility headers
|
||||
When using Spring Data Elasticsearch 4 - which uses the Elasticsearch 7 client libraries - and accessing an Elasticsearch cluster that is running on version 8, it is necessary to set the compatibility headers
|
||||
https://www.elastic.co/guide/en/elasticsearch/reference/8.0/rest-api-compatibility.html[see Elasticsearch
|
||||
documentation].
|
||||
|
||||
For the imperative client this must be done by setting the default headers, for the reactive code this must be done using a header supplier:
|
||||
|
||||
CAUTION: Even when these headers are set, there are cases where the response returned from the cluster cannot be
|
||||
parsed with the client. This is not an error in Spring Data Elasticsearch.
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@@ -333,13 +182,12 @@ ClientConfiguration clientConfiguration = ClientConfiguration.builder()
|
||||
[[elasticsearch.clients.logging]]
|
||||
== Client Logging
|
||||
|
||||
To see what is actually sent to and received from the server `Request` / `Response` logging on the transport level
|
||||
needs to be turned on as outlined in the snippet below. This can be enabled in the Elasticsearch client by setting
|
||||
the level of the `tracer` package to "trace" (see
|
||||
https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/java-rest-low-usage-logging.html)
|
||||
To see what is actually sent to and received from the server `Request` / `Response` logging on the transport level needs to be turned on as outlined in the snippet below.
|
||||
|
||||
.Enable transport layer logging
|
||||
[source,xml]
|
||||
----
|
||||
<logger name="tracer" level="trace"/>
|
||||
<logger name="org.springframework.data.elasticsearch.client.WIRE" level="trace"/>
|
||||
----
|
||||
|
||||
NOTE: The above applies to both the `RestHighLevelClient` and `ReactiveElasticsearchClient` when obtained via `RestClients` respectively `ReactiveRestClients`.
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
|
||||
Spring Data Elasticsearch supports the https://www.elastic.co/guide/en/elasticsearch/reference/current/parent-join.html[Join data type] for creating the corresponding index mappings and for storing the relevant information.
|
||||
|
||||
[[elasticsearch.jointype.setting-up]]
|
||||
== Setting up the data
|
||||
|
||||
For an entity to be used in a parent child join relationship, it must have a property of type `JoinField` which must be annotated.
|
||||
@@ -161,7 +160,6 @@ Spring Data Elasticsearch will build the following mapping for this class:
|
||||
----
|
||||
====
|
||||
|
||||
[[elasticsearch.jointype.storing]]
|
||||
== Storing data
|
||||
|
||||
Given a repository for this class the following code inserts a question, two answers, a comment and a vote:
|
||||
@@ -211,10 +209,9 @@ void init() {
|
||||
<5> a vote for the first answer, this needs to have the routing set to the weather document, see <<elasticsearch.routing>>.
|
||||
====
|
||||
|
||||
[[elasticsearch.jointype.retrieving]]
|
||||
== Retrieving data
|
||||
|
||||
Currently native queries must be used to query the data, so there is no support from standard repository methods. <<repositories.custom-implementations>> can be used instead.
|
||||
Currently native search queries must be used to query the data, so there is no support from standard repository methods. <<repositories.custom-implementations>> can be used instead.
|
||||
|
||||
The following code shows as an example how to retrieve all entries that have a _vote_ (which must be _answers_, because only answers can have a vote) using an `ElasticsearchOperations` instance:
|
||||
|
||||
@@ -222,17 +219,11 @@ The following code shows as an example how to retrieve all entries that have a _
|
||||
[source,java]
|
||||
----
|
||||
SearchHits<Statement> hasVotes() {
|
||||
NativeSearchQuery query = new NativeSearchQueryBuilder()
|
||||
.withQuery(hasChildQuery("vote", matchAllQuery(), ScoreMode.None))
|
||||
.build();
|
||||
|
||||
Query query = NativeQuery.builder()
|
||||
.withQuery(co.elastic.clients.elasticsearch._types.query_dsl.Query.of(qb -> qb
|
||||
.hasChild(hc -> hc
|
||||
.queryName("vote")
|
||||
.query(matchAllQueryAsQuery())
|
||||
.scoreMode(ChildScoreMode.None)
|
||||
)))
|
||||
.build();
|
||||
|
||||
return operations.search(query, Statement.class);
|
||||
return operations.search(query, Statement.class);
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
@@ -95,7 +95,6 @@ default boolean createIndex(String indexName) {
|
||||
[[elasticsearch-migration-guide-3.2-4.0.deprecations]]
|
||||
== Deprecations
|
||||
|
||||
[[elasticsearch-migration-guide-3.2-4.0.deprecations.methods-classes]]
|
||||
=== Methods and classes
|
||||
|
||||
Many functions and classes have been deprecated. These functions still work, but the Javadocs show with what they should be replaced.
|
||||
@@ -116,7 +115,6 @@ Many functions and classes have been deprecated. These functions still work, but
|
||||
<T> T queryForObject(GetQuery query, Class<T> clazz);
|
||||
----
|
||||
|
||||
[[elasticsearch-migration-guide-3.2-4.0.deprecations.elasticsearch]]
|
||||
=== Elasticsearch deprecations
|
||||
|
||||
Since version 7 the Elasticsearch `TransportClient` is deprecated, it will be removed with Elasticsearch version 8. Spring Data Elasticsearch deprecates the `ElasticsearchTemplate` class which uses the `TransportClient` in version 4.0.
|
||||
|
||||
@@ -9,7 +9,7 @@ This section describes breaking changes from version 4.0.x to 4.1.x and how remo
|
||||
.Definition of the id property
|
||||
It is possible to define a property of en entity as the id property by naming it either `id` or `document`.
|
||||
This behaviour is now deprecated and will produce a warning.
|
||||
Please use the `@Id` annotation to mark a property as being the id property.
|
||||
PLease us the `@Id` annotation to mark a property as being the id property.
|
||||
|
||||
.Index mappings
|
||||
In the `ReactiveElasticsearchClient.Indices` interface the `updateMapping` methods are deprecated in favour of the `putMapping` methods.
|
||||
@@ -32,7 +32,6 @@ They had been deprecated in Spring Data Elasticsearch 4.0 and their values weren
|
||||
[[elasticsearch-migration-guide-4.0-4.1.breaking-changes]]
|
||||
== Breaking Changes
|
||||
|
||||
[[elasticsearch-migration-guide-4.0-4.1.breaking-changes.returntypes-1]]
|
||||
=== Return types of ReactiveElasticsearchClient.Indices methods
|
||||
|
||||
The methods in the `ReactiveElasticsearchClient.Indices` were not used up to now.
|
||||
@@ -41,8 +40,7 @@ With the introduction of the `ReactiveIndexOperations` it became necessary to ch
|
||||
* the `createIndex` variants now return a `Mono<Boolean>` instead of a `Mono<Void>` to signal successful index creation.
|
||||
* the `updateMapping` variants now return a `Mono<Boolean>` instead of a `Mono<Void>` to signal successful mappings storage.
|
||||
|
||||
[[elasticsearch-migration-guide-4.0-4.1.breaking-changes.returntypes-2]]
|
||||
=== Return types of DocumentOperations.bulkIndex methods
|
||||
=== Return types of DocumentOperartions.bulkIndex methods
|
||||
|
||||
These methods were returning a `List<String>` containing the ids of the new indexed records.
|
||||
These methods were returing a `List<String>` containing the ids of the new indexed records.
|
||||
Now they return a `List<IndexedObjectInformation>`; these objects contain the id and information about optimistic locking (seq_no and primary_term)
|
||||
|
||||
@@ -6,7 +6,6 @@ This section describes breaking changes from version 4.1.x to 4.2.x and how remo
|
||||
[[elasticsearch-migration-guide-4.1-4.2.deprecations]]
|
||||
== Deprecations
|
||||
|
||||
[[elasticsearch-migration-guide-4.1-4.2.deprecations.document]]
|
||||
=== @Document parameters
|
||||
|
||||
The parameters of the `@Document` annotation that are relevant for the index settings (`useServerConfiguration`, `shards`. `replicas`, `refreshIntervall` and `indexStoretype`) have been moved to the `@Setting` annotation. Use in `@Document` is still possible but deprecated.
|
||||
@@ -15,7 +14,7 @@ The parameters of the `@Document` annotation that are relevant for the index se
|
||||
== Removals
|
||||
|
||||
The `@Score` annotation that was used to set the score return value in an entity was deprecated in version 4.0 and has been removed.
|
||||
Score values are returned in the `SearchHit` instances that encapsulate the returned entities.
|
||||
Scroe values are returned in the `SearchHit` instances that encapsulate the returned entities.
|
||||
|
||||
The `org.springframework.data.elasticsearch.ElasticsearchException` class has been removed.
|
||||
The remaining usages have been replaced with `org.springframework.data.mapping.MappingException` and `org.springframework.dao.InvalidDataAccessApiUsageException`.
|
||||
@@ -29,10 +28,8 @@ The deprecated `find` methods from `ReactiveSearchOperations` and `ReactiveDocum
|
||||
[[elasticsearch-migration-guide-4.1-4.2.breaking-changes]]
|
||||
== Breaking Changes
|
||||
|
||||
[[elasticsearch-migration-guide-4.1-4.2.breaking-changes.refresh-policy]]
|
||||
=== RefreshPolicy
|
||||
|
||||
[[elasticsearch-migration-guide-4.1-4.2.breaking-changes.refresh-policy.enum]]
|
||||
==== Enum package changed
|
||||
|
||||
It was possible in 4.1 to configure the refresh policy for the `ReactiveElasticsearchTemplate` by overriding the method `AbstractReactiveElasticsearchConfiguration.refreshPolicy()` in a custom configuration class.
|
||||
@@ -41,7 +38,6 @@ The return value of this method was an instance of the class `org.elasticsearch.
|
||||
Now the configuration must return `org.springframework.data.elasticsearch.core.RefreshPolicy`.
|
||||
This enum has the same values and triggers the same behaviour as before, so only the `import` statement has to be adjusted.
|
||||
|
||||
[[elasticsearch-migration-guide-4.1-4.2.breaking-changes.refresh-policy.behaviour]]
|
||||
==== Refresh behaviour
|
||||
|
||||
`ElasticsearchOperations` and `ReactiveElasticsearchOperations` now explicitly use the `RefreshPolicy` set on the template for write requests if not null.
|
||||
@@ -51,21 +47,17 @@ The provided implementations for `ElasticsearchRepository` and `ReactiveElastics
|
||||
This is the same behaviour as in previous versions.
|
||||
If a refresh policy is set, then it will be used by the repositories as well.
|
||||
|
||||
[[elasticsearch-migration-guide-4.1-4.2.breaking-changes.refresh-policy.configuration]]
|
||||
==== Refresh configuration
|
||||
|
||||
When configuring Spring Data Elasticsearch like described in <<elasticsearch.clients>> by using `ElasticsearchConfigurationSupport`, `AbstractElasticsearchConfiguration` or `AbstractReactiveElasticsearchConfiguration` the refresh policy will be initialized to `null`.
|
||||
Previously the reactive code initialized this to `IMMEDIATE`, now reactive and non-reactive code show the same behaviour.
|
||||
|
||||
[[elasticsearch-migration-guide-4.1-4.2.breaking-changes.method-return-types]]
|
||||
=== Method return types
|
||||
|
||||
[[elasticsearch-migration-guide-4.1-4.2.breaking-changes.method-return-types.delete]]
|
||||
==== delete methods that take a Query
|
||||
|
||||
The reactive methods previously returned a `Mono<Long>` with the number of deleted documents, the non reactive versions were void. They now return a `Mono<ByQueryResponse>` which contains much more detailed information about the deleted documents and errors that might have occurred.
|
||||
|
||||
[[elasticsearch-migration-guide-4.1-4.2.breaking-changes.method-return-types.multiget]]
|
||||
==== multiget methods
|
||||
|
||||
The implementations of _multiget_ previousl only returned the found entities in a `List<T>` for non-reactive implementations and in a `Flux<T>` for reactive implementations. If the request contained ids that were not found, the information that these are missing was not available. The user needed to compare the returned ids to the requested ones to find
|
||||
|
||||
@@ -21,7 +21,6 @@ Check the sections on <<elasticsearch-migration-guide-4.2-4.3.deprecations>> and
|
||||
[[elasticsearch-migration-guide-4.2-4.3.deprecations]]
|
||||
== Deprecations
|
||||
|
||||
[[elasticsearch-migration-guide-4.2-4.3.deprecations.suggest]]
|
||||
=== suggest methods
|
||||
|
||||
In `SearchOperations`, and so in `ElasticsearchOperations` as well, the `suggest` methods taking a `org.elasticsearch.search.suggest.SuggestBuilder` as argument and returning a `org.elasticsearch.action.search.SearchResponse` have been deprecated.
|
||||
@@ -33,7 +32,6 @@ Here as well the old methods are deprecated.
|
||||
[[elasticsearch-migration-guide-4.2-4.3.breaking-changes]]
|
||||
== Breaking Changes
|
||||
|
||||
[[elasticsearch-migration-guide-4.2-4.3.breaking-changes.1]]
|
||||
=== Removal of `org.elasticsearch` classes from the API.
|
||||
|
||||
* In the `org.springframework.data.elasticsearch.annotations.CompletionContext` annotation the property `type()` has changed from `org.elasticsearch.search.suggest.completion.context.ContextMapping.Type` to `org.springframework.data.elasticsearch.annotations.CompletionContext.ContextMappingType`, the available enum values are the same.
|
||||
@@ -48,7 +46,6 @@ The same change has been done to the `ReactiveSearchOperations.aggregate()` func
|
||||
Programs using the aggregations need to be changed to cast the returned value to the appropriate class to further proces it.
|
||||
* methods that might have thrown a `org.elasticsearch.ElasticsearchStatusException` now will throw `org.springframework.data.elasticsearch.RestStatusException` instead.
|
||||
|
||||
[[elasticsearch-migration-guide-4.2-4.3.breaking-changes.2]]
|
||||
=== Handling of field and sourceFilter properties of Query
|
||||
|
||||
Up to version 4.2 the `fields` property of a `Query` was interpreted and added to the include list of the `sourceFilter`.
|
||||
@@ -56,13 +53,11 @@ This was not correct, as these are different things for Elasticsearch.
|
||||
This has been corrected.
|
||||
As a consequence code might not work anymore that relies on using `fields` to specify which fields should be returned from the document's `_source' and should be changed to use the `sourceFilter`.
|
||||
|
||||
[[elasticsearch-migration-guide-4.2-4.3.breaking-changes.3]]
|
||||
=== search_type default value
|
||||
|
||||
The default value for the `search_type` in Elasticsearch is `query_then_fetch`.
|
||||
This now is also set as default value in the `Query` implementations, it was previously set to `dfs_query_then_fetch`.
|
||||
|
||||
[[elasticsearch-migration-guide-4.2-4.3.breaking-changes.4]]
|
||||
=== BulkOptions changes
|
||||
|
||||
Some properties of the `org.springframework.data.elasticsearch.core.query.BulkOptions` class have changed their type:
|
||||
@@ -70,17 +65,14 @@ Some properties of the `org.springframework.data.elasticsearch.core.query.BulkOp
|
||||
* the type of the `timeout` property has been changed to `java.time.Duration`.
|
||||
* the type of the`refreshPolicy` property has been changed to `org.springframework.data.elasticsearch.core.RefreshPolicy`.
|
||||
|
||||
[[elasticsearch-migration-guide-4.2-4.3.breaking-changes.5]]
|
||||
=== IndicesOptions change
|
||||
|
||||
Spring Data Elasticsearch now uses `org.springframework.data.elasticsearch.core.query.IndicesOptions` instead of `org.elasticsearch.action.support.IndicesOptions`.
|
||||
|
||||
[[elasticsearch-migration-guide-4.2-4.3.breaking-changes.6]]
|
||||
=== Completion classes
|
||||
|
||||
The classes from the package `org.springframework.data.elasticsearch.core.completion` have been moved to `org.springframework.data.elasticsearch.core.suggest`.
|
||||
|
||||
[[elasticsearch-migration-guide-4.2-4.3.breaking-changes.7]]
|
||||
=== Other renamings
|
||||
|
||||
The `org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentPropertyConverter` interface has been renamed to `org.springframework.data.elasticsearch.core.mapping.PropertyValueConverter`.
|
||||
|
||||
@@ -6,7 +6,6 @@ This section describes breaking changes from version 4.3.x to 4.4.x and how remo
|
||||
[[elasticsearch-migration-guide-4.3-4.4.deprecations]]
|
||||
== Deprecations
|
||||
|
||||
[[elasticsearch-migration-guide-4.3-4.4.deprecations.reactive-operations]]
|
||||
=== org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations
|
||||
|
||||
The method `<T> Publisher<T> execute(ClientCallback<Publisher<T>> callback)` has been deprecated.
|
||||
@@ -15,7 +14,6 @@ As there now are multiple implementations using different client libraries the `
|
||||
[[elasticsearch-migration-guide-4.3-4.4.breaking-changes]]
|
||||
== Breaking Changes
|
||||
|
||||
[[elasticsearch-migration-guide-4.3-4.4.breaking-changes.1]]
|
||||
=== Removal of deprecated classes
|
||||
|
||||
==== `org.springframework.data.elasticsearch.core.ElasticsearchTemplate` has been removed
|
||||
@@ -25,13 +23,11 @@ This means that the `org.springframework.data.elasticsearch.core.ElasticsearchTe
|
||||
This was the implementation of the `ElasticsearchOperations` interface that was using the `TransportClient`.
|
||||
Connections to Elasticsearch must be made using either the imperative `ElasticsearchRestTemplate` or the reactive `ReactiveElasticsearchTemplate`.
|
||||
|
||||
[[elasticsearch-migration-guide-4.3-4.4.breaking-changes.2]]
|
||||
=== Package changes
|
||||
|
||||
In 4.3 two classes (`ElasticsearchAggregations` and `ElasticsearchAggregation`) had been moved to the `org.springframework.data.elasticsearch.core.clients.elasticsearch7` package in preparation for the integration of the new Elasticsearch client.
|
||||
The were moved back to the `org.springframework.data.elasticsearch.core` package as we keep the classes use the old Elasticsearch client where they were.
|
||||
|
||||
[[elasticsearch-migration-guide-4.3-4.4.breaking-changes.3]]
|
||||
=== Behaviour change
|
||||
|
||||
The `ReactiveElasticsearchTemplate`, when created directly or by Spring Boot configuration had a default refresh policy of IMMEDIATE.
|
||||
@@ -50,7 +46,6 @@ Spring Data Elasticsearch 4.4 still uses the old client as the default client fo
|
||||
* There are still some bugs in the Elasticsearch client which need to be resolved
|
||||
* The implementation using the new client in Spring Data Elasticsearch is not yet complete, due to limited resources working on that - remember Spring Data Elasticsearch is a community driven project that lives from public contributions.
|
||||
|
||||
[[elasticsearch-migration-guide-4.3-4.4.new-clients.how-to]]
|
||||
=== How to use the new client
|
||||
|
||||
CAUTION: The implementation using the new client is not complete, some operations will throw a `java.lang.UnsupportedOperationException` or might throw NPE (for example when the Elasticsearch cannot parse a response from the server, this still happens sometimes) +
|
||||
@@ -58,7 +53,6 @@ Use the new client to test the implementations but do not use it in productive c
|
||||
|
||||
In order to try and use the new client the following steps are necessary:
|
||||
|
||||
[[elasticsearch-migration-guide-4.3-4.4.new-clients.how-to.not]]
|
||||
==== Make sure not to configure the existing default client
|
||||
|
||||
If using Spring Boot, exclude Spring Data Elasticsearch from the autoconfiguration
|
||||
@@ -75,9 +69,8 @@ public class SpringdataElasticTestApplication {
|
||||
====
|
||||
|
||||
Remove Spring Data Elasticsearch related properties from your application configuration.
|
||||
If Spring Data Elasticsearch was configured using a programmatic configuration (see <<elasticsearch.clients>>), remove these beans from the Spring application context.
|
||||
If Spring Data Elasticsearch was configured using a programmatic configuration (see <<elastisearch.clients>>), remove these beans from the Spring application context.
|
||||
|
||||
[[elasticsearch-migration-guide-4.3-4.4.new-clients.how-to.dependencies]]
|
||||
==== Add dependencies
|
||||
|
||||
The dependencies for the new Elasticsearch client are still optional in Spring Data Elasticsearch so they need to be added explicitly:
|
||||
@@ -89,7 +82,7 @@ The dependencies for the new Elasticsearch client are still optional in Spring D
|
||||
<dependency>
|
||||
<groupId>co.elastic.clients</groupId>
|
||||
<artifactId>elasticsearch-java</artifactId>
|
||||
<version>7.17.3</version>
|
||||
<version>7.17.6</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>commons-logging</groupId>
|
||||
@@ -100,7 +93,7 @@ The dependencies for the new Elasticsearch client are still optional in Spring D
|
||||
<dependency>
|
||||
<groupId>org.elasticsearch.client</groupId>
|
||||
<artifactId>elasticsearch-rest-client</artifactId> <!-- is Apache 2-->
|
||||
<version>7.17.3</version>
|
||||
<version>7.17.6</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>commons-logging</groupId>
|
||||
@@ -123,10 +116,8 @@ When using Spring Boot, it is necessary to set the following property in the _po
|
||||
----
|
||||
====
|
||||
|
||||
[[elasticsearch-migration-guide-4.3-4.4.new-clients.how-to.configuration]]
|
||||
==== New configuration classes
|
||||
|
||||
[[elasticsearch-migration-guide-4.3-4.4.new-clients.how-to.configuration.imperative]]
|
||||
===== Imperative style
|
||||
|
||||
In order configure Spring Data Elasticsearch to use the new client, it is necessary to create a configuration bean that derives from `org.springframework.data.elasticsearch.client.elc.ElasticsearchConfiguration`:
|
||||
@@ -154,7 +145,6 @@ With this configuration, the following beans will be available in the Spring app
|
||||
* an `ElasticsearchClient` bean, this is the new client that uses the `RestClient`
|
||||
* an `ElasticsearchOperations` bean, available with the bean names _elasticsearchOperations_ and _elasticsearchTemplate_, this uses the `ElasticsearchClient`
|
||||
|
||||
[[elasticsearch-migration-guide-4.3-4.4.new-clients.how-to.configuration.reactive]]
|
||||
===== Reactive style
|
||||
|
||||
To use the new client in a reactive environment the only difference is the class from which to derive the configuration:
|
||||
|
||||
@@ -1,168 +0,0 @@
|
||||
[[elasticsearch-migration-guide-4.4-5.0]]
|
||||
= Upgrading from 4.4.x to 5.0.x
|
||||
|
||||
This section describes breaking changes from version 4.4.x to 5.0.x and how removed features can be replaced by new introduced features.
|
||||
|
||||
[[elasticsearch-migration-guide-4.4-4.5.deprecations]]
|
||||
== Deprecations
|
||||
|
||||
=== Custom trace level logging
|
||||
|
||||
Logging by setting the property `logging.level.org.springframework.data.elasticsearch.client.WIRE=trace` is
|
||||
deprecated now, the Elasticsearch `RestClient` provides a better solution that can be activated by setting the
|
||||
logging level of the `tracer` package to "trace".
|
||||
|
||||
[[elasticsearch-migration-guide-4.4-4.5.deprecations.package]]
|
||||
=== `org.springframework.data.elasticsearch.client.erhlc` package
|
||||
|
||||
See <<elasticsearch-migration-guide-4.4-5.0.breaking-changes-packages>>, all classes in this package have been deprecated, as the default client implementations to use are the ones based on the new Java Client from Elasticsearch, see <<elasticsearch-migration-guide-4.4-5.0.new-clients>>
|
||||
|
||||
[[elasticsearch-migration-guide-4.4-4.5.deprecations.code]]
|
||||
=== Removal of deprecated code
|
||||
|
||||
`DateFormat.none` and `DateFormat.custom` had been deprecated since version 4.2 and have been removed.
|
||||
|
||||
The properties of `@Document` that were deprecated since 4.2 have been removed.
|
||||
Use the `@Settings` annotation for these.
|
||||
|
||||
`@DynamicMapping` and `@DynamicMappingValue` have been removed.
|
||||
Use `@Document.dynamic` or `@Field.dynamic` instead.
|
||||
|
||||
[[elasticsearch-migration-guide-4.4-5.0.breaking-changes]]
|
||||
== Breaking Changes
|
||||
|
||||
[[elasticsearch-migration-guide-4.4-5.0.breaking-changes.deprecated-calls]]
|
||||
=== Removal of deprecated calls
|
||||
|
||||
[[elasticsearch-migration-guide-4.4-5.0.breaking-changes.deprecated-calls.1]]
|
||||
==== suggest calls in operations interfaces have been removed
|
||||
|
||||
Both `SearchOperations` and `ReactiveSearchOperations` had deprecated calls that were using Elasticsearch classes as parameters.
|
||||
These now have been removed and so the dependency on Elasticsearch classes in these APIs has been cleaned.
|
||||
|
||||
[[elasticsearch-migration-guide-4.4-5.0.breaking-changes-packages]]
|
||||
=== Package changes
|
||||
|
||||
All the classes that are using or depend on the deprecated Elasticsearch `RestHighLevelClient` have been moved to the package `org.springframework.data.elasticsearch.client.erhlc`.
|
||||
By this change we now have a clear separation of code using the old deprecated Elasticsearch libraries, code using the new Elasticsearch client and code that is independent of the client implementation.
|
||||
Also the reactive implementation that was provided up to now has been moved here, as this implementation contains code that was copied and adapted from Elasticsearch libraries.
|
||||
|
||||
If you are using `ElasticsearchRestTemplate` directly and not the `ElasticsearchOperations` interface you'll need to adjust your imports as well.
|
||||
|
||||
When working with the `NativeSearchQuery` class, you'll need to switch to the `NativeQuery` class, which can take a
|
||||
`Query` instance comign from the new Elasticsearch client libraries.
|
||||
You'll find plenty of examples in the test code.
|
||||
|
||||
[[elasticsearch-migration-guide-4.4-5.0.breaking-changes-records]]
|
||||
=== Conversion to Java 17 records
|
||||
|
||||
The following classes have been converted to `Record`, you might need to adjust the use of getter methods from
|
||||
`getProp()` to `prop()`:
|
||||
|
||||
* `org.springframework.data.elasticsearch.core.AbstractReactiveElasticsearchTemplate.IndexResponseMetaData`
|
||||
* `org.springframework.data.elasticsearch.core.ActiveShardCount`
|
||||
* `org.springframework.data.elasticsearch.support.Version`
|
||||
* `org.springframework.data.elasticsearch.support.ScoreDoc`
|
||||
* `org.springframework.data.elasticsearch.core.query.ScriptData`
|
||||
* `org.springframework.data.elasticsearch.core.query.SeqNoPrimaryTerm`
|
||||
|
||||
[[elasticsearch-migration-guide-4.4-5.0.breaking-changes-http-headers]]
|
||||
=== New HttpHeaders class
|
||||
|
||||
Until version 4.4 the client configuration used the `HttpHeaders` class from the `org.springframework:spring-web`
|
||||
project.
|
||||
This introduces a dependency on that artifact.
|
||||
Users that do not use spring-web then face an error as this class cannot be found.
|
||||
|
||||
In version 5.0 we introduce our own `HttpHeaders` to configure the clients.
|
||||
|
||||
So if you are using headers in the client configuration, you need to replace `org.springframework.http.HttpHeaders`
|
||||
with `org.springframework.data.elasticsearch.support.HttpHeaders`.
|
||||
|
||||
Hint: You can pass a `org.springframework.http
|
||||
.HttpHeaders` to the `addAll()` method of `org.springframework.data.elasticsearch.support.HttpHeaders`.
|
||||
|
||||
[[elasticsearch-migration-guide-4.4-5.0.new-clients]]
|
||||
== New Elasticsearch client
|
||||
|
||||
Spring Data Elasticsearch now uses the new `ElasticsearchClient` and has deprecated the use of the previous `RestHighLevelClient`.
|
||||
|
||||
[[elasticsearch-migration-guide-4.4-5.0.new-clients.imperative]]
|
||||
=== Imperative style configuration
|
||||
|
||||
To configure Spring Data Elasticsearch to use the new client, it is necessary to create a configuration bean that derives from `org.springframework.data.elasticsearch.client.elc.ElasticsearchConfiguration`:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@Configuration
|
||||
public class NewRestClientConfig extends ElasticsearchConfiguration {
|
||||
|
||||
@Override
|
||||
public ClientConfiguration clientConfiguration() {
|
||||
return ClientConfiguration.builder() //
|
||||
.connectedTo("localhost:9200") //
|
||||
.build();
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
The configuration is done in the same way as with the old client, but it is not necessary anymore to create more than the configuration bean.
|
||||
With this configuration, the following beans will be available in the Spring application context:
|
||||
|
||||
* a `RestClient` bean, that is the configured low level `RestClient` that is used by the Elasticsearch client
|
||||
* an `ElasticsearchClient` bean, this is the new client that uses the `RestClient`
|
||||
* an `ElasticsearchOperations` bean, available with the bean names _elasticsearchOperations_ and _elasticsearchTemplate_, this uses the `ElasticsearchClient`
|
||||
|
||||
[[elasticsearch-migration-guide-4.4-5.0.new-clients.reactive]]
|
||||
=== Reactive style configuration
|
||||
|
||||
To use the new client in a reactive environment the only difference is the class from which to derive the configuration:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@Configuration
|
||||
public class NewRestClientConfig extends ReactiveElasticsearchConfiguration {
|
||||
|
||||
@Override
|
||||
public ClientConfiguration clientConfiguration() {
|
||||
return ClientConfiguration.builder() //
|
||||
.connectedTo("localhost:9200") //
|
||||
.build();
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
With this configuration, the following beans will be available in the Spring application context:
|
||||
|
||||
* a `RestClient` bean, that is the configured low level `RestClient` that is used by the Elasticsearch client
|
||||
* an `ReactiveElasticsearchClient` bean, this is the new reactive client that uses the `RestClient`
|
||||
* an `ReactiveElasticsearchOperations` bean, available with the bean names _reactiveElasticsearchOperations_ and _reactiveElasticsearchTemplate_, this uses the `ReactiveElasticsearchClient`
|
||||
|
||||
[[elasticsearch-migration-guide-4.4-5.0.old-client]]
|
||||
=== Still want to use the old client?
|
||||
|
||||
The old deprecated `RestHighLevelClient` can still be used, but you will need to add the dependency explicitly to your application as Spring Data Elasticsearch does not pull it in automatically anymore:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<!-- include the RHLC, specify version explicitly -->
|
||||
<dependency>
|
||||
<groupId>org.elasticsearch.client</groupId>
|
||||
<artifactId>elasticsearch-rest-high-level-client</artifactId>
|
||||
<version>7.17.5</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>commons-logging</groupId>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
----
|
||||
====
|
||||
|
||||
Make sure to specify the version 7.17.6 explicitly, otherwise maven will resolve to 8.5.0, and this does not exist.
|
||||
@@ -1,26 +0,0 @@
|
||||
[[elasticsearch-migration-guide-5.0-5.1]]
|
||||
= Upgrading from 5.0.x to 5.1.x
|
||||
|
||||
This section describes breaking changes from version 5.0.x to 5.1.x and how removed features can be replaced by new introduced features.
|
||||
|
||||
[[elasticsearch-migration-guide-5.0-5.1.breaking-changes]]
|
||||
== Breaking Changes
|
||||
|
||||
In the `org.springframework.data.elasticsearch.core.index.AliasData` class, which is used for alias information returned from Elasticsearch, the property `filter` (of type `Document`) is replaced by `filterQuery` which is of type
|
||||
`org.springframework.data.elasticsearch.core.query.Query`.
|
||||
|
||||
`org.springframework.data.elasticsearch.annotations.Similarity` was an enum class until 5.1. This enum was used in the `@Field` annotation to specify a similarity value.
|
||||
But besides the values defined by the enum, it is possible to have similarities with custom names in Elasticsearch.
|
||||
Therefore, the annotation property was changed from the type of the enum to a simple `String`.
|
||||
The previous enum values like `Similarity.Default` do still exist as String constants, so existing code will compile unmodified.
|
||||
Adaptions are necessary when this enum was used at other places than as a property of the `@Field` annotation.
|
||||
|
||||
[[elasticsearch-migration-guide-5.0-5.1.deprecations]]
|
||||
== Deprecations
|
||||
|
||||
=== template functions
|
||||
|
||||
The functions in the `IndexOperations` and `ReactiverIndexOperations` to manage index templates that were introduced in Spring Data Elasticsearch 4.1
|
||||
have been deprecated. They were using the old Elasticsearch API that was deprecated in Elasticsearch version 7.8.
|
||||
|
||||
Please use the new functions that are based on the compsable index template API instead.
|
||||
@@ -17,6 +17,7 @@ The following arguments are available:
|
||||
* `refreshIntervall`, defaults to _"1s"_
|
||||
* `indexStoreType`, defaults to _"fs"_
|
||||
|
||||
|
||||
It is as well possible to define https://www.elastic.co/guide/en/elasticsearch/reference/7.11/index-modules-index-sorting.html[index sorting] (check the linked Elasticsearch documentation for the possible field types and values):
|
||||
|
||||
====
|
||||
@@ -86,19 +87,12 @@ private ElasticsearchOperations operations;
|
||||
|
||||
IndexCoordinates index = IndexCoordinates.of("sample-index");
|
||||
|
||||
Query query = NativeQuery.builder()
|
||||
.withQuery(q -> q
|
||||
.matchAll(ma -> ma))
|
||||
.withFilter( q -> q
|
||||
.bool(b -> b
|
||||
.must(m -> m
|
||||
.term(t -> t
|
||||
.field("id")
|
||||
.value(documentId))
|
||||
)))
|
||||
.build();
|
||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
||||
.withQuery(matchAllQuery())
|
||||
.withFilter(boolFilter().must(termFilter("id", documentId)))
|
||||
.build();
|
||||
|
||||
SearchHits<SampleEntity> sampleEntities = operations.search(query, SampleEntity.class, index);
|
||||
Page<SampleEntity> sampleEntities = operations.searchForPage(searchQuery, SampleEntity.class, index);
|
||||
----
|
||||
====
|
||||
|
||||
@@ -113,15 +107,13 @@ This is internally used by Spring Data Elasticsearch to provide the implementati
|
||||
----
|
||||
IndexCoordinates index = IndexCoordinates.of("sample-index");
|
||||
|
||||
Query searchQuery = NativeQuery.builder()
|
||||
.withQuery(q -> q
|
||||
.matchAll(ma -> ma))
|
||||
.withFields("message")
|
||||
.withPageable(PageRequest.of(0, 10))
|
||||
.build();
|
||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
||||
.withQuery(matchAllQuery())
|
||||
.withFields("message")
|
||||
.withPageable(PageRequest.of(0, 10))
|
||||
.build();
|
||||
|
||||
SearchHitsIterator<SampleEntity> stream = elasticsearchOperations.searchForStream(searchQuery, SampleEntity.class,
|
||||
index);
|
||||
SearchHitsIterator<SampleEntity> stream = elasticsearchTemplate.searchForStream(searchQuery, SampleEntity.class, index);
|
||||
|
||||
List<SampleEntity> sampleEntities = new ArrayList<>();
|
||||
while (stream.hasNext()) {
|
||||
@@ -132,26 +124,23 @@ stream.close();
|
||||
----
|
||||
====
|
||||
|
||||
There are no methods in the `SearchOperations` API to access the scroll id, if it should be necessary to access this, the following methods of the `AbstractElasticsearchTemplate` can be used (this is the base implementation for the different `ElasticsearchOperations` implementations):
|
||||
There are no methods in the `SearchOperations` API to access the scroll id, if it should be necessary to access this, the following methods of the `ElasticsearchRestTemplate` can be used:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
|
||||
@Autowired ElasticsearchOperations operations;
|
||||
|
||||
AbstractElasticsearchTemplate template = (AbstractElasticsearchTemplate)operations;
|
||||
@Autowired ElasticsearchRestTemplate template;
|
||||
|
||||
IndexCoordinates index = IndexCoordinates.of("sample-index");
|
||||
|
||||
Query query = NativeQuery.builder()
|
||||
.withQuery(q -> q
|
||||
.matchAll(ma -> ma))
|
||||
.withFields("message")
|
||||
.withPageable(PageRequest.of(0, 10))
|
||||
.build();
|
||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
||||
.withQuery(matchAllQuery())
|
||||
.withFields("message")
|
||||
.withPageable(PageRequest.of(0, 10))
|
||||
.build();
|
||||
|
||||
SearchScrollHits<SampleEntity> scroll = template.searchScrollStart(1000, query, SampleEntity.class, index);
|
||||
SearchScrollHits<SampleEntity> scroll = template.searchScrollStart(1000, searchQuery, SampleEntity.class, index);
|
||||
|
||||
String scrollId = scroll.getScrollId();
|
||||
List<SampleEntity> sampleEntities = new ArrayList<>();
|
||||
@@ -201,7 +190,6 @@ Sort.by(new GeoDistanceOrder("location", new GeoPoint(48.137154, 11.5761247)))
|
||||
From version 7.12 on Elasticsearch has added the feature of runtime fields (https://www.elastic.co/guide/en/elasticsearch/reference/7.12/runtime.html).
|
||||
Spring Data Elasticsearch supports this in two ways:
|
||||
|
||||
[[elasticsearch.misc.runtime-fields.index-mappings]]
|
||||
=== Runtime field definitions in the index mappings
|
||||
|
||||
The first way to define runtime fields is by adding the definitions to the index mappings (see https://www.elastic.co/guide/en/elasticsearch/reference/7.12/runtime-mapping-fields.html).
|
||||
@@ -236,7 +224,6 @@ public class RuntimeFieldEntity {
|
||||
----
|
||||
====
|
||||
|
||||
[[elasticsearch.misc.runtime-fields.query]]
|
||||
=== Runtime fields definitions set on a Query
|
||||
|
||||
The second way to define runtime fields is by adding the definitions to a search query (see https://www.elastic.co/guide/en/elasticsearch/reference/7.12/runtime-search-request.html).
|
||||
@@ -274,148 +261,3 @@ SearchHits<SomethingToBuy> searchHits = operations.search(query, SomethingToBuy.
|
||||
====
|
||||
|
||||
This works with every implementation of the `Query` interface.
|
||||
|
||||
[[elasticsearch.misc.point-in-time]]
|
||||
== Point In Time (PIT) API
|
||||
|
||||
`ElasticsearchOperations` supports the point in time API of Elasticsearch (see https://www.elastic.co/guide/en/elasticsearch/reference/8.3/point-in-time-api.html).
|
||||
The following code snippet shows how to use this feature with a fictional `Person` class:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
ElasticsearchOperations operations; // autowired
|
||||
Duration tenSeconds = Duration.ofSeconds(10);
|
||||
|
||||
String pit = operations.openPointInTime(IndexCoordinates.of("person"), tenSeconds); <.>
|
||||
|
||||
// create query for the pit
|
||||
Query query1 = new CriteriaQueryBuilder(Criteria.where("lastName").is("Smith"))
|
||||
.withPointInTime(new Query.PointInTime(pit, tenSeconds)) <.>
|
||||
.build();
|
||||
SearchHits<Person> searchHits1 = operations.search(query1, Person.class);
|
||||
// do something with the data
|
||||
|
||||
// create 2nd query for the pit, use the id returned in the previous result
|
||||
Query query2 = new CriteriaQueryBuilder(Criteria.where("lastName").is("Miller"))
|
||||
.withPointInTime(
|
||||
new Query.PointInTime(searchHits1.getPointInTimeId(), tenSeconds)) <.>
|
||||
.build();
|
||||
SearchHits<Person> searchHits2 = operations.search(query2, Person.class);
|
||||
// do something with the data
|
||||
|
||||
operations.closePointInTime(searchHits2.getPointInTimeId()); <.>
|
||||
|
||||
----
|
||||
|
||||
<.> create a point in time for an index (can be multiple names) and a keep-alive duration and retrieve its id
|
||||
<.> pass that id into the query to search together with the next keep-alive value
|
||||
<.> for the next query, use the id returned from the previous search
|
||||
<.> when done, close the point in time using the last returned id
|
||||
====
|
||||
|
||||
[[elasticsearch.misc.searchtemplates]]
|
||||
== Search Template support
|
||||
|
||||
Use of the search template API is supported.
|
||||
To use this, it first is necessary to create a stored script.
|
||||
The `ElasticsearchOperations` interface extends `ScriptOperations` which provides the necessary functions.
|
||||
The example used here assumes that we have `Person` entity with a property named `firstName`.
|
||||
A search template script can be saved like this:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
|
||||
import org.springframework.data.elasticsearch.core.script.Script;
|
||||
|
||||
operations.putScript( <.>
|
||||
Script.builder()
|
||||
.withId("person-firstname") <.>
|
||||
.withLanguage("mustache") <.>
|
||||
.withSource(""" <.>
|
||||
{
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"match": {
|
||||
"firstName": "{{firstName}}" <.>
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"from": "{{from}}", <.>
|
||||
"size": "{{size}}" <.>
|
||||
}
|
||||
""")
|
||||
.build()
|
||||
);
|
||||
----
|
||||
|
||||
<.> Use the `putScript()` method to store a search template script
|
||||
<.> The name / id of the script
|
||||
<.> Scripts that are used in search templates must be in the _mustache_ language.
|
||||
<.> The script source
|
||||
<.> The search parameter in the script
|
||||
<.> Paging request offset
|
||||
<.> Paging request size
|
||||
====
|
||||
|
||||
To use a search template in a search query, Spring Data Elasticsearch provides the `SearchTemplateQuery`, an implementation of the `org.springframework.data.elasticsearch.core.query.Query` interface.
|
||||
|
||||
In the following code, we will add a call using a search template query to a custom repository implementation (see
|
||||
<<repositories.custom-implementations>>) as
|
||||
an example how this can be integrated into a repository call.
|
||||
|
||||
We first define the custom repository fragment interface:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
interface PersonCustomRepository {
|
||||
SearchPage<Person> findByFirstNameWithSearchTemplate(String firstName, Pageable pageable);
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
The implementation of this repository fragment looks like this:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
public class PersonCustomRepositoryImpl implements PersonCustomRepository {
|
||||
|
||||
private final ElasticsearchOperations operations;
|
||||
|
||||
public PersonCustomRepositoryImpl(ElasticsearchOperations operations) {
|
||||
this.operations = operations;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SearchPage<Person> findByFirstNameWithSearchTemplate(String firstName, Pageable pageable) {
|
||||
|
||||
var query = SearchTemplateQuery.builder() <.>
|
||||
.withId("person-firstname") <.>
|
||||
.withParams(
|
||||
Map.of( <.>
|
||||
"firstName", firstName,
|
||||
"from", pageable.getOffset(),
|
||||
"size", pageable.getPageSize()
|
||||
)
|
||||
)
|
||||
.build();
|
||||
|
||||
SearchHits<Person> searchHits = operations.search(query, Person.class); <.>
|
||||
|
||||
return SearchHitSupport.searchPageFor(searchHits, pageable);
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
<.> Create a `SearchTemplateQuery`
|
||||
<.> Provide the id of the search template
|
||||
<.> The parameters are passed in a `Map<String,Object>`
|
||||
<.> Do the search in the same way as with the other query types.
|
||||
====
|
||||
|
||||
@@ -1,25 +1,11 @@
|
||||
[[new-features]]
|
||||
= What's new
|
||||
|
||||
[[new-features.5-1-0]]
|
||||
== New in Spring Data Elasticsearch 5.1
|
||||
|
||||
* Upgrade to Elasticsearch 8.7.0
|
||||
* Allow specification of the TLS certificate when connecting to an Elasticsearch 8 cluster
|
||||
|
||||
[[new-features.5-0-0]]
|
||||
== New in Spring Data Elasticsearch 5.0
|
||||
|
||||
* Upgrade to Java 17 baseline
|
||||
* Upgrade to Spring Framework 6
|
||||
* Upgrade to Elasticsearch 8.5.0
|
||||
* Use the new Elasticsearch client library
|
||||
|
||||
[[new-features.4-4-0]]
|
||||
== New in Spring Data Elasticsearch 4.4
|
||||
|
||||
* Introduction of new imperative and reactive clients using the classes from the new Elasticsearch Java client
|
||||
* Upgrade to Elasticsearch 7.17.3.
|
||||
* Upgrade to Elasticsearch 7.17.6.
|
||||
|
||||
[[new-features.4-3-0]]
|
||||
== New in Spring Data Elasticsearch 4.3
|
||||
|
||||
@@ -2,8 +2,19 @@
|
||||
= Elasticsearch Object Mapping
|
||||
|
||||
Spring Data Elasticsearch Object Mapping is the process that maps a Java object - the domain entity - into the JSON representation that is stored in Elasticsearch and back.
|
||||
The class that is internally used for this mapping is the
|
||||
`MappingElasticsearchConverter`.
|
||||
|
||||
Earlier versions of Spring Data Elasticsearch used a Jackson based conversion, Spring Data Elasticsearch 3.2.x introduced the <<elasticsearch.mapping.meta-model>>.
|
||||
As of version 4.0 only the Meta Object Mapping is used, the Jackson based mapper is not available anymore and the `MappingElasticsearchConverter` is used.
|
||||
|
||||
The main reasons for the removal of the Jackson based mapper are:
|
||||
|
||||
* Custom mappings of fields needed to be done with annotations like `@JsonFormat` or `@JsonInclude`.
|
||||
This often caused problems when the same object was used in different JSON based datastores or sent over a JSON based API.
|
||||
* Custom field types and formats also need to be stored into the Elasticsearch index mappings.
|
||||
The Jackson based annotations did not fully provide all the information that is necessary to represent the types of Elasticsearch.
|
||||
* Fields must be mapped not only when converting from and to entities, but also in query argument, returned data and on other places.
|
||||
|
||||
Using the `MappingElasticsearchConverter` now covers all these cases.
|
||||
|
||||
[[elasticsearch.mapping.meta-model]]
|
||||
== Meta Model Object Mapping
|
||||
@@ -20,16 +31,17 @@ The metadata is taken from the entity's properties which can be annotated.
|
||||
The following annotations are available:
|
||||
|
||||
* `@Document`: Applied at the class level to indicate this class is a candidate for mapping to the database.
|
||||
The most important attributes are (check the API documentation for the complete list of attributes):
|
||||
The most important attributes are:
|
||||
** `indexName`: the name of the index to store this entity in.
|
||||
This can contain a SpEL template expression like `"log-#{T(java.time.LocalDate).now().toString()}"`
|
||||
** `createIndex`: flag whether to create an index on repository bootstrapping.
|
||||
Default value is _true_.
|
||||
See <<elasticsearch.repositories.autocreation>>
|
||||
|
||||
** `versionType`: Configuration of version management.
|
||||
Default value is _EXTERNAL_.
|
||||
|
||||
* `@Id`: Applied at the field level to mark the field used for identity purpose.
|
||||
* `@Transient`, `@ReadOnlyProperty`, `@WriteOnlyProperty`: see the following section <<elasticsearch.mapping.meta-model.annotations.read-write>> for detailed information.
|
||||
* `@Transient`: By default all fields are mapped to the document when it is stored or retrieved, this annotation excludes the field.
|
||||
* `@PersistenceConstructor`: Marks a given constructor - even a package protected one - to use when instantiating the object from the database.
|
||||
Constructor arguments are mapped by name to the key values in the retrieved Document.
|
||||
* `@Field`: Applied at the field level and defines properties of the field, most of the attributes map to the respective https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping.html[Elasticsearch Mapping] definitions (the following list is not complete, check the annotation Javadoc for a complete reference):
|
||||
@@ -38,8 +50,8 @@ Constructor arguments are mapped by name to the key values in the retrieved Docu
|
||||
See https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-types.html[Elasticsearch Mapping Types].
|
||||
If the field type is not specified, it defaults to `FieldType.Auto`.
|
||||
This means, that no mapping entry is written for the property and that Elasticsearch will add a mapping entry dynamically when the first data for this property is stored (check the Elasticsearch documentation for dynamic mapping rules).
|
||||
** `format`: One or more built-in date formats, see the next section <<elasticsearch.mapping.meta-model.annotations.date-formats>>.
|
||||
** `pattern`: One or more custom date formats, see the next section <<elasticsearch.mapping.meta-model.annotations.date-formats>>.
|
||||
** `format`: One or more built-in date formats, see the next section <<elasticsearch.mapping.meta-model.date-formats>>.
|
||||
** `pattern`: One or more custom date formats, see the next section <<elasticsearch.mapping.meta-model.date-formats>>.
|
||||
** `store`: Flag whether the original field value should be store in Elasticsearch, default value is _false_.
|
||||
** `analyzer`, `searchAnalyzer`, `normalizer` for specifying custom analyzers and normalizer.
|
||||
* `@GeoPoint`: Marks a field as _geo_point_ datatype.
|
||||
@@ -49,20 +61,7 @@ In difference to a registered Spring `Converter` this only converts the annotate
|
||||
|
||||
The mapping metadata infrastructure is defined in a separate spring-data-commons project that is technology agnostic.
|
||||
|
||||
[[elasticsearch.mapping.meta-model.annotations.read-write]]
|
||||
==== Controlling which properties are written to and read from Elasticsearch
|
||||
|
||||
This section details the annotations that define if the value of a property is written to or read from Elasticsearch.
|
||||
|
||||
`@Transient`: A property annotated with this annotation will not be written to the mapping, it's value will not be sent to Elasticsearch and when documents are returned from Elasticsearch, this property will not be set in the resulting entity.
|
||||
|
||||
`@ReadOnlyProperty`: A property with this annotaiton will not have its value written to Elasticsearch, but when returning data, the proeprty will be filled with the value returned in the document from Elasticsearch.
|
||||
One use case for this are runtime fields defined in the index mapping.
|
||||
|
||||
`@WriteOnlyProperty`: A property with this annotaiton will have its value stored in Elasticsearch but will not be set with any value when reading document.
|
||||
This can be used for example for synthesized fields which should go into the Elasticsearch index but are not used elsewhere.
|
||||
|
||||
[[elasticsearch.mapping.meta-model.annotations.date-formats]]
|
||||
[[elasticsearch.mapping.meta-model.date-formats]]
|
||||
==== Date format mapping
|
||||
|
||||
Properties that derive from `TemporalAccessor` or are of type `java.util.Date` must either have a `@Field` annotation of type `FieldType.Date` or a custom converter must be registered for this type.
|
||||
@@ -104,9 +103,6 @@ The following table shows the different attributes and the mapping created from
|
||||
NOTE: If you are using a custom date format, you need to use _uuuu_ for the year instead of _yyyy_.
|
||||
This is due to a https://www.elastic.co/guide/en/elasticsearch/reference/current/migrate-to-java-time.html#java-time-migration-incompatible-date-formats[change in Elasticsearch 7].
|
||||
|
||||
Check the code of the `org.springframework.data.elasticsearch.annotations.DateFormat` enum for a complete list of predefined values and their patterns.
|
||||
|
||||
[[elasticsearch.mapping.meta-model.annotations.range]]
|
||||
==== Range types
|
||||
|
||||
When a field is annotated with a type of one of _Integer_Range, Float_Range, Long_Range, Double_Range, Date_Range,_ or _Ip_Range_ the field must be an instance of a class that will be mapped to an Elasticsearch range, for example:
|
||||
@@ -152,7 +148,6 @@ class SomePersonData {
|
||||
Supported classes for the type `<T>` are `Integer`, `Long`, `Float`, `Double`, `Date` and classes that implement the
|
||||
`TemporalAccessor` interface.
|
||||
|
||||
[[elasticsearch.mapping.meta-model.annotations.mapped-names]]
|
||||
==== Mapped field names
|
||||
|
||||
Without further configuration, Spring Data Elasticsearch will use the property name of an object as field name in Elasticsearch.
|
||||
@@ -162,45 +157,9 @@ It is also possible to define a `FieldNamingStrategy` in the configuration of th
|
||||
If for example a `SnakeCaseFieldNamingStrategy` is configured, the property _sampleProperty_ of the object would be mapped to _sample_property_ in Elasticsearch.
|
||||
A `FieldNamingStrategy` applies to all entities; it can be overwritten by setting a specific name with `@Field` on a property.
|
||||
|
||||
[[elasticsearch.mapping.meta-model.annotations.non-field-backed-properties]]
|
||||
==== Non-field-backed properties
|
||||
|
||||
Normally the properties used in an entity are fields of the entity class.
|
||||
There might be cases, when a property value is calculated in the entity and should be stored in Elasticsearch.
|
||||
In this case, the getter method (`getProperty()`) can be annotated with the `@Field` annotation, in addition to that the method must be annotated with `@AccessType(AccessType.Type
|
||||
.PROPERTY)`.
|
||||
The third annotation that is needed in such a case is `@WriteOnlyProperty`, as such a value is only written to Elasticsearch.
|
||||
A full example:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@Field(type = Keyword)
|
||||
@WriteOnlyProperty
|
||||
@AccessType(AccessType.Type.PROPERTY)
|
||||
public String getProperty() {
|
||||
return "some value that is calculated here";
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
[[elasticsearch.mapping.meta-model.annotations.misc]]
|
||||
==== Other property annotations
|
||||
|
||||
===== @IndexedIndexName
|
||||
|
||||
This annotation can be set on a String property of an entity.
|
||||
This property will not be written to the mapping, it will not be stored in Elasticsearch and its value will not be read from an Elasticsearch document.
|
||||
After an entity is persisted, for example with a call to `ElasticsearchOperations.save(T entity)`, the entity
|
||||
returned from that call will contain the name of the index that an entity was saved to in that property.
|
||||
This is useful when the index name is dynamically set by a bean, or when writing to a write alias.
|
||||
|
||||
Putting some value into such a property does not set the index into which an entity is stored!
|
||||
|
||||
[[elasticsearch.mapping.meta-model.rules]]
|
||||
=== Mapping Rules
|
||||
|
||||
[[elasticsearch.mapping.meta-model.rules.typehints]]
|
||||
==== Type Hints
|
||||
|
||||
Mapping uses _type hints_ embedded in the document sent to the server to allow generic type mapping.
|
||||
@@ -211,6 +170,7 @@ Those type hints are represented as `_class` attributes within the document and
|
||||
[source,java]
|
||||
----
|
||||
public class Person { <1>
|
||||
|
||||
@Id String id;
|
||||
String firstname;
|
||||
String lastname;
|
||||
@@ -267,7 +227,7 @@ In this case, writing the type hint will produce an error, as the field cannot b
|
||||
|
||||
Type hints can be disabled for the whole application by overriding the method `writeTypeHints()` in a configuration class derived from `AbstractElasticsearchConfiguration` (see <<elasticsearch.clients>>).
|
||||
|
||||
As an alternative they can be disabled for a single index with the `@Document` annotation:
|
||||
As an alternativ they can be disabled for a single index with the `@Document` annotation:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
@@ -280,7 +240,6 @@ WARNING: We strongly advise against disabling Type Hints.
|
||||
Only do this if you are forced to.
|
||||
Disabling type hints can lead to documents not being retrieved correctly from Elasticsearch in case of polymorphic data or document retrieval may fail completely.
|
||||
|
||||
[[elasticsearch.mapping.meta-model.rules.geospatial]]
|
||||
==== Geospatial Types
|
||||
|
||||
Geospatial types like `Point` & `GeoPoint` are converted into _lat/lon_ pairs.
|
||||
@@ -290,6 +249,7 @@ Geospatial types like `Point` & `GeoPoint` are converted into _lat/lon_ pairs.
|
||||
[source,java]
|
||||
----
|
||||
public class Address {
|
||||
|
||||
String city, street;
|
||||
Point location;
|
||||
}
|
||||
@@ -305,7 +265,6 @@ public class Address {
|
||||
----
|
||||
====
|
||||
|
||||
[[elasticsearch.mapping.meta-model.rules.geojson]]
|
||||
==== GeoJson Types
|
||||
|
||||
Spring Data Elasticsearch supports the GeoJson types by providing an interface `GeoJson` and implementations for the different geometries.
|
||||
@@ -346,7 +305,6 @@ The following GeoJson types are implemented:
|
||||
* `GeoJsonMultiPolygon`
|
||||
* `GeoJsonGeometryCollection`
|
||||
|
||||
[[elasticsearch.mapping.meta-model.rules.collections]]
|
||||
==== Collections
|
||||
|
||||
For values inside Collections apply the same mapping rules as for aggregate roots when it comes to _type hints_ and <<elasticsearch.mapping.meta-model.conversions>>.
|
||||
@@ -374,7 +332,6 @@ public class Person {
|
||||
----
|
||||
====
|
||||
|
||||
[[elasticsearch.mapping.meta-model.rules.maps]]
|
||||
==== Maps
|
||||
|
||||
For values inside Maps apply the same mapping rules as for aggregate roots when it comes to _type hints_ and <<elasticsearch.mapping.meta-model.conversions>>.
|
||||
@@ -419,15 +376,12 @@ Looking at the `Configuration` from the <<elasticsearch.mapping.meta-model, prev
|
||||
[source,java]
|
||||
----
|
||||
@Configuration
|
||||
public class Config extends ElasticsearchConfiguration {
|
||||
public class Config extends AbstractElasticsearchConfiguration {
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public ClientConfiguration clientConfiguration() {
|
||||
return ClientConfiguration.builder() //
|
||||
.connectedTo("localhost:9200") //
|
||||
.build();
|
||||
}
|
||||
@Override
|
||||
public RestHighLevelClient elasticsearchClient() {
|
||||
return RestClients.create(ClientConfiguration.create("localhost:9200")).rest();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Override
|
||||
@@ -438,7 +392,7 @@ public class Config extends ElasticsearchConfiguration {
|
||||
|
||||
@WritingConverter <2>
|
||||
static class AddressToMap implements Converter<Address, Map<String, Object>> {
|
||||
|
||||
|
||||
@Override
|
||||
public Map<String, Object> convert(Address source) {
|
||||
|
||||
|
||||
@@ -30,11 +30,36 @@ There is support for automatic creation of indices and writing the mappings when
|
||||
|
||||
====
|
||||
|
||||
[[elasticsearch.operations.resttemplate]]
|
||||
== ElasticsearchRestTemplate
|
||||
|
||||
The `ElasticsearchRestTemplate` is an implementation of the `ElasticsearchOperations` interface using the <<elasticsearch.clients.rest>>.
|
||||
|
||||
.ElasticsearchRestTemplate configuration
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@Configuration
|
||||
public class RestClientConfig extends AbstractElasticsearchConfiguration {
|
||||
@Override
|
||||
public RestHighLevelClient elasticsearchClient() { <1>
|
||||
return RestClients.create(ClientConfiguration.localhost()).rest();
|
||||
}
|
||||
|
||||
// no special bean creation needed <2>
|
||||
}
|
||||
----
|
||||
|
||||
<1> Setting up the <<elasticsearch.clients.rest>>.
|
||||
<2> The base class `AbstractElasticsearchConfiguration` already provides the `elasticsearchTemplate` bean.
|
||||
====
|
||||
|
||||
[[elasticsearch.operations.usage]]
|
||||
== Usage examples
|
||||
|
||||
As both `ElasticsearchTemplate` and `ElasticsearchRestTemplate` implement the `ElasticsearchOperations` interface, the code to use them is not different.
|
||||
The example shows how to use an injected `ElasticsearchOperations` instance in a Spring REST controller.
|
||||
The example assumes that `Person` is a class that is annotated with `@Document`, `@Id` etc (see <<elasticsearch.mapping.meta-model.annotations>>).
|
||||
The decision, if this is using the `TransportClient` or the `RestClient` is made by providing the corresponding Bean with one of the configurations shown above.
|
||||
|
||||
.ElasticsearchOperations usage
|
||||
====
|
||||
@@ -46,29 +71,34 @@ public class TestController {
|
||||
|
||||
private ElasticsearchOperations elasticsearchOperations;
|
||||
|
||||
public TestController(ElasticsearchOperations elasticsearchOperations) { <.>
|
||||
public TestController(ElasticsearchOperations elasticsearchOperations) { <1>
|
||||
this.elasticsearchOperations = elasticsearchOperations;
|
||||
}
|
||||
|
||||
@PostMapping("/person")
|
||||
public String save(@RequestBody Person person) { <.>
|
||||
Person savedEntity = elasticsearchOperations.save(person);
|
||||
return savedEntity.getId();
|
||||
public String save(@RequestBody Person person) { <2>
|
||||
|
||||
IndexQuery indexQuery = new IndexQueryBuilder()
|
||||
.withId(person.getId().toString())
|
||||
.withObject(person)
|
||||
.build();
|
||||
String documentId = elasticsearchOperations.index(indexQuery);
|
||||
return documentId;
|
||||
}
|
||||
|
||||
@GetMapping("/person/{id}")
|
||||
public Person findById(@PathVariable("id") Long id) { <.>
|
||||
Person person = elasticsearchOperations.get(id.toString(), Person.class);
|
||||
public Person findById(@PathVariable("id") Long id) { <3>
|
||||
Person person = elasticsearchOperations
|
||||
.queryForObject(GetQuery.getById(id.toString()), Person.class);
|
||||
return person;
|
||||
}
|
||||
}
|
||||
|
||||
----
|
||||
|
||||
<.> Let Spring inject the provided `ElasticsearchOperations` bean in the constructor.
|
||||
<.> Store some entity in the Elasticsearch cluster.
|
||||
The id is read from the returned entity, as it might have been null in the `person` object and been created by Elasticsearch.
|
||||
<.> Retrieve the entity with a get by id.
|
||||
<1> Let Spring inject the provided `ElasticsearchOperations` bean in the constructor.
|
||||
<2> Store some entity in the Elasticsearch cluster.
|
||||
<3> Retrieve the entity with a query by id.
|
||||
====
|
||||
|
||||
To see the full possibilities of `ElasticsearchOperations` please refer to the API documentation.
|
||||
@@ -120,7 +150,7 @@ An Iterator returned by the streaming functions of the `SearchOperations` interf
|
||||
[[elasticsearch.operations.queries]]
|
||||
== Queries
|
||||
|
||||
Almost all of the methods defined in the `SearchOperations` and `ReactiveSearchOperations` interface take a `Query` parameter that defines the query to execute for searching. `Query` is an interface and Spring Data Elasticsearch provides three implementations: `CriteriaQuery`, `StringQuery` and `NativeQuery`.
|
||||
Almost all of the methods defined in the `SearchOperations` and `ReactiveSearchOperations` interface take a `Query` parameter that defines the query to execute for searching. `Query` is an interface and Spring Data Elasticsearch provides three implementations: `CriteriaQuery`, `StringQuery` and `NativeSearchQuery`.
|
||||
|
||||
[[elasticsearch.operations.criteriaquery]]
|
||||
=== CriteriaQuery
|
||||
@@ -147,7 +177,7 @@ Conditions for the same field can be chained, they will be combined with a logic
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
Criteria criteria = new Criteria("price").greaterThan(42.0).lessThan(34.0);
|
||||
Criteria criteria = new Criteria("price").greaterThan(42.0).lessThan(34.0L);
|
||||
Query query = new CriteriaQuery(criteria);
|
||||
----
|
||||
====
|
||||
@@ -200,7 +230,7 @@ The following code shows a query that searches for persons having the first name
|
||||
[source,java]
|
||||
----
|
||||
|
||||
Query query = new StringQuery("{ \"match\": { \"firstname\": { \"query\": \"Jack\" } } } ");
|
||||
Query query = new SearchQuery("{ \"match\": { \"firstname\": { \"query\": \"Jack\" } } } ");
|
||||
SearchHits<Person> searchHits = operations.search(query, Person.class);
|
||||
|
||||
----
|
||||
@@ -208,35 +238,22 @@ SearchHits<Person> searchHits = operations.search(query, Person.class);
|
||||
|
||||
Using `StringQuery` may be appropriate if you already have an Elasticsearch query to use.
|
||||
|
||||
[[elasticsearch.operations.nativequery]]
|
||||
=== NativeQuery
|
||||
[[elasticsearch.operations.nativesearchquery]]
|
||||
=== NativeSearchQuery
|
||||
|
||||
`NativeQuery` is the class to use when you have a complex query, or a query that cannot be expressed by using the `Criteria` API, for example when building queries and using aggregates.
|
||||
It allows to use all the different `co.elastic.clients.elasticsearch._types.query_dsl.Query` implementations from the Elasticsearch library therefore named "native".
|
||||
`NativeSearchQuery` is the class to use when you have a complex query, or a query that cannot be expressed by using the `Criteria` API, for example when building queries and using aggregates.
|
||||
It allows to use all the different `QueryBuilder` implementations from the Elasticsearch library therefore named "native".
|
||||
|
||||
The following code shows how to search for persons with a given firstname and for the found documents have a terms aggregation that counts the number of occurences of the lastnames for these persons:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
Query query = NativeQuery.builder()
|
||||
.withAggregation("lastNames", Aggregation.of(a -> a
|
||||
.terms(ta -> ta.field("last-name").size(10))))
|
||||
.withQuery(q -> q
|
||||
.match(m -> m
|
||||
.field("firstName")
|
||||
.query(firstName)
|
||||
)
|
||||
)
|
||||
.withPageable(pageable)
|
||||
.build();
|
||||
Query query = new NativeSearchQueryBuilder()
|
||||
.addAggregation(terms("lastnames").field("lastname").size(10)) //
|
||||
.withQuery(QueryBuilders.matchQuery("firstname", firstName))
|
||||
.build();
|
||||
|
||||
SearchHits<Person> searchHits = operations.search(query, Person.class);
|
||||
----
|
||||
====
|
||||
|
||||
[[elasticsearch.operations.searchtemplateScOp§query]]
|
||||
=== SearchTemplateQuery
|
||||
|
||||
This is a special implementation of the `Query` interface to be used in combination with a stored search template.
|
||||
See <<elasticsearch.misc.searchtemplates>> for further information.
|
||||
|
||||
@@ -40,7 +40,6 @@ include::reactive-elasticsearch-repositories.adoc[leveloffset=+1]
|
||||
[[elasticsearch.repositories.annotations]]
|
||||
== Annotations for repository methods
|
||||
|
||||
[[elasticsearch.repositories.annotations.highlight]]
|
||||
=== @Highlight
|
||||
|
||||
The `@Highlight` annotation on a repository method defines for which fields of the returned entity highlighting should be included. To search for some text in a `Book` 's name or summary and have the found data highlighted, the following repository method can be used:
|
||||
@@ -54,7 +53,7 @@ interface BookRepository extends Repository<Book, String> {
|
||||
@HighlightField(name = "name"),
|
||||
@HighlightField(name = "summary")
|
||||
})
|
||||
SearchHits<Book> findByNameOrSummary(String text, String summary);
|
||||
List<SearchHit<Book>> findByNameOrSummary(String text, String summary);
|
||||
}
|
||||
----
|
||||
====
|
||||
@@ -63,31 +62,6 @@ It is possible to define multiple fields to be highlighted like above, and both
|
||||
|
||||
In the search results the highlight data can be retrieved from the `SearchHit` class.
|
||||
|
||||
[[elasticsearch.repositories.annotations.sourcefilters]]
|
||||
=== @SourceFilters
|
||||
|
||||
Sometimes the user does not need to have all the properties of an entity returned from a search but only a subset.
|
||||
Elasticsearch provides source filtering to reduce the amount of data that is transferred across the network to the
|
||||
application.
|
||||
|
||||
When working with `Query` implementations and the `ElasticsearchOperations` this is easily possible by setting a
|
||||
source filter on the query.
|
||||
|
||||
When using repository methods there is the `@SourceFilters` annotation:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
interface BookRepository extends Repository<Book, String> {
|
||||
|
||||
@SourceFilters(includes = "name")
|
||||
SearchHits<Book> findByName(String text);
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
In this example, all the properties of the returned `Book` objects would be `null` except the name.
|
||||
|
||||
[[elasticsearch.annotation]]
|
||||
== Annotation based configuration
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
|
||||
The Elasticsearch module supports all basic query building feature as string queries, native search queries, criteria based queries or have it being derived from the method name.
|
||||
|
||||
[[elasticsearch.query-methods.finders.declared]]
|
||||
=== Declared queries
|
||||
|
||||
Deriving the query from the method name is not always sufficient and/or may result in unreadable method names.
|
||||
@@ -299,7 +298,6 @@ A list of supported keywords for Elasticsearch is shown below.
|
||||
NOTE: Methods names to build Geo-shape queries taking `GeoJson` parameters are not supported.
|
||||
Use `ElasticsearchOperations` with `CriteriaQuery` in a custom repository implementation if you need to have such a function in a repository.
|
||||
|
||||
[[elasticsearch.query-methods.return-types]]
|
||||
== Method return types
|
||||
|
||||
Repository methods can be defined to have the following return types for returning multiple Elements:
|
||||
@@ -361,3 +359,4 @@ would make an https://www.elastic.co/guide/en/elasticsearch/reference/current/qu
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
[[elasticsearch.routing]]
|
||||
= Routing values
|
||||
|
||||
@@ -7,7 +8,6 @@ For this Elasticsearch offers the possibility to define a routing, which is the
|
||||
|
||||
Spring Data Elasticsearch supports routing definitions on storing and retrieving data in the following ways:
|
||||
|
||||
[[elasticsearch.routing.join-types]]
|
||||
== Routing on join-types
|
||||
|
||||
When using join-types (see <<elasticsearch.jointype>>), Spring Data Elasticsearch will automatically use the `parent` property of the entity's `JoinField` property as the value for the routing.
|
||||
@@ -15,7 +15,6 @@ When using join-types (see <<elasticsearch.jointype>>), Spring Data Elasticsearc
|
||||
This is correct for all the use-cases where the parent-child relationship has just one level.
|
||||
If it is deeper, like a child-parent-grandparent relationship - like in the above example from _vote_ -> _answer_ -> _question_ - then the routing needs to explicitly specified by using the techniques described in the next section (the _vote_ needs the _question.id_ as routing value).
|
||||
|
||||
[[elasticsearch.routing.custom]]
|
||||
== Custom routing values
|
||||
|
||||
To define a custom routing for an entity, Spring Data Elasticsearch provides a `@Routing` annotation (reusing the `Statement` class from above):
|
||||
@@ -104,3 +103,4 @@ operations.withRouting(RoutingResolver.just(routing)).delete(id);
|
||||
----
|
||||
<.> `RoutingResolver.just(s)` returns a resolver that will just return the given String.
|
||||
====
|
||||
|
||||
|
||||
@@ -12,9 +12,4 @@ include::elasticsearch-migration-guide-4.1-4.2.adoc[]
|
||||
include::elasticsearch-migration-guide-4.2-4.3.adoc[]
|
||||
|
||||
include::elasticsearch-migration-guide-4.3-4.4.adoc[]
|
||||
|
||||
include::elasticsearch-migration-guide-4.4-5.0.adoc[]
|
||||
|
||||
include::elasticsearch-migration-guide-5.0-5.1.adoc[]
|
||||
|
||||
:leveloffset: -1
|
||||
|
||||
@@ -5,22 +5,80 @@
|
||||
|
||||
The `ReactiveElasticsearchTemplate` is the default implementation of `ReactiveElasticsearchOperations`.
|
||||
|
||||
[[elasticsearch.reactive.operations]]
|
||||
== Reactive Elasticsearch Operations
|
||||
[[elasticsearch.reactive.template]]
|
||||
== Reactive Elasticsearch Template
|
||||
|
||||
To get started the `ReactiveElasticsearchOperations` needs to know about the actual client to work with.
|
||||
Please see <<elasticsearch.clients.reactiverestclient>> for details on the client and how to configure it.
|
||||
To get started the `ReactiveElasticsearchTemplate` needs to know about the actual client to work with.
|
||||
Please see <<elasticsearch.clients.reactive>> for details on the client.
|
||||
|
||||
[[elasticsearch.reactive.operations.usage]]
|
||||
=== Reactive Operations Usage
|
||||
[[elasticsearch.reactive.template.configuration]]
|
||||
=== Reactive Template Configuration
|
||||
|
||||
`ReactiveElasticsearchOperations` lets you save, find and delete your domain objects and map those objects to documents
|
||||
stored
|
||||
in Elasticsearch.
|
||||
The easiest way of setting up the `ReactiveElasticsearchTemplate` is via `AbstractReactiveElasticsearchConfiguration` providing
|
||||
dedicated configuration method hooks for `base package`, the `initial entity set` etc.
|
||||
|
||||
.The AbstractReactiveElasticsearchConfiguration
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@Configuration
|
||||
public class Config extends AbstractReactiveElasticsearchConfiguration {
|
||||
|
||||
@Bean <1>
|
||||
@Override
|
||||
public ReactiveElasticsearchClient reactiveElasticsearchClient() {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
----
|
||||
<1> Configure the client to use. This can be done by `ReactiveRestClients` or directly via `DefaultReactiveElasticsearchClient`.
|
||||
====
|
||||
|
||||
NOTE: If applicable set default `HttpHeaders` via the `ClientConfiguration` of the `ReactiveElasticsearchClient`. See <<elasticsearch.clients.configuration>>.
|
||||
|
||||
TIP: If needed the `ReactiveElasticsearchTemplate` can be configured with default `RefreshPolicy` and `IndicesOptions` that get applied to the related requests by overriding the defaults of `refreshPolicy()` and `indicesOptions()`.
|
||||
|
||||
However one might want to be more in control over the actual components and use a more verbose approach.
|
||||
|
||||
.Configure the ReactiveElasticsearchTemplate
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@Configuration
|
||||
public class Config {
|
||||
|
||||
@Bean <1>
|
||||
public ReactiveElasticsearchClient reactiveElasticsearchClient() {
|
||||
// ...
|
||||
}
|
||||
@Bean <2>
|
||||
public ElasticsearchConverter elasticsearchConverter() {
|
||||
return new MappingElasticsearchConverter(elasticsearchMappingContext());
|
||||
}
|
||||
@Bean <3>
|
||||
public SimpleElasticsearchMappingContext elasticsearchMappingContext() {
|
||||
return new SimpleElasticsearchMappingContext();
|
||||
}
|
||||
@Bean <4>
|
||||
public ReactiveElasticsearchOperations reactiveElasticsearchOperations() {
|
||||
return new ReactiveElasticsearchTemplate(reactiveElasticsearchClient(), elasticsearchConverter());
|
||||
}
|
||||
}
|
||||
----
|
||||
<1> Configure the client to use. This can be done by `ReactiveRestClients` or directly via `DefaultReactiveElasticsearchClient`.
|
||||
<2> Set up the `ElasticsearchConverter` used for domain type mapping utilizing metadata provided by the mapping context.
|
||||
<3> The Elasticsearch specific mapping context for domain type metadata.
|
||||
<4> The actual template based on the client and conversion infrastructure.
|
||||
====
|
||||
|
||||
[[elasticsearch.reactive.template.usage]]
|
||||
=== Reactive Template Usage
|
||||
|
||||
`ReactiveElasticsearchTemplate` lets you save, find and delete your domain objects and map those objects to documents stored in Elasticsearch.
|
||||
|
||||
Consider the following:
|
||||
|
||||
.Use the ReactiveElasticsearchOperations
|
||||
.Use the ReactiveElasticsearchTemplate
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@@ -36,20 +94,15 @@ public class Person {
|
||||
|
||||
[source,java]
|
||||
----
|
||||
|
||||
ReactiveElasticsearchOperations operations;
|
||||
|
||||
// ...
|
||||
|
||||
operations.save(new Person("Bruce Banner", 42)) <.>
|
||||
template.save(new Person("Bruce Banner", 42)) <1>
|
||||
.doOnNext(System.out::println)
|
||||
.flatMap(person -> operations.get(person.id, Person.class)) <.>
|
||||
.flatMap(person -> template.findById(person.id, Person.class)) <2>
|
||||
.doOnNext(System.out::println)
|
||||
.flatMap(person -> operations.delete(person)) <.>
|
||||
.flatMap(person -> template.delete(person)) <3>
|
||||
.doOnNext(System.out::println)
|
||||
.flatMap(id -> operations.count(Person.class)) <.>
|
||||
.flatMap(id -> template.count(Person.class)) <4>
|
||||
.doOnNext(System.out::println)
|
||||
.subscribe(); <.>
|
||||
.subscribe(); <5>
|
||||
----
|
||||
|
||||
The above outputs the following sequence on the console.
|
||||
@@ -61,10 +114,11 @@ The above outputs the following sequence on the console.
|
||||
> QjWCWWcBXiLAnp77ksfR
|
||||
> 0
|
||||
----
|
||||
<.> Insert a new `Person` document into the _marvel_ index . The `id` is generated on server
|
||||
side and set into the instance returned.
|
||||
<.> Lookup the `Person` with matching `id` in the _marvel_ index.
|
||||
<.> Delete the `Person` with matching `id`, extracted from the given instance, in the _marvel_ index.
|
||||
<.> Count the total number of documents in the _marvel_ index.
|
||||
<.> Don't forget to _subscribe()_.
|
||||
<1> Insert a new `Person` document into the _marvel_ index under type _characters_. The `id` is generated on server side and set into the instance returned.
|
||||
<2> Lookup the `Person` with matching `id` in the _marvel_ index under type _characters_.
|
||||
<3> Delete the `Person` with matching `id`, extracted from the given instance, in the _marvel_ index under type _characters_.
|
||||
<4> Count the total number of documents in the _marvel_ index under type _characters_.
|
||||
<5> Don't forget to _subscribe()_.
|
||||
====
|
||||
|
||||
|
||||
|
||||
@@ -79,7 +79,7 @@ interface ReactivePersonRepository extends ReactiveSortingRepository<Person, Str
|
||||
parameters.
|
||||
<9> Count all entities with matching `firstname`.
|
||||
<10> Check if at least one entity with matching `firstname` exists.
|
||||
<11> Delete all entities with matching `firstname`.
|
||||
<11> Delete all entites with matching `firstname`.
|
||||
====
|
||||
|
||||
[[elasticsearch.reactive.repositories.configuration]]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2020-2023 the original author or authors.
|
||||
* Copyright 2020-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2022-2023 the original author or authors.
|
||||
* Copyright 2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -15,10 +15,10 @@
|
||||
*/
|
||||
package org.springframework.data.elasticsearch;
|
||||
|
||||
import org.springframework.lang.Nullable;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
/**
|
||||
* Object describing an Elasticsearch error
|
||||
*
|
||||
@@ -26,8 +26,7 @@ import java.util.List;
|
||||
* @since 4.4
|
||||
*/
|
||||
public class ElasticsearchErrorCause {
|
||||
@Nullable
|
||||
private final String type;
|
||||
@Nullable private final String type;
|
||||
|
||||
private final String reason;
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2019-2023 the original author or authors.
|
||||
* Copyright 2019-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
/*
|
||||
* Copyright 2022-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.elasticsearch;
|
||||
|
||||
import org.springframework.dao.NonTransientDataAccessResourceException;
|
||||
|
||||
/**
|
||||
* @author Peter-Josef Meisch
|
||||
* @since 5.1
|
||||
*/
|
||||
public class ResourceNotFoundException extends NonTransientDataAccessResourceException {
|
||||
|
||||
public ResourceNotFoundException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2020-2023 the original author or authors.
|
||||
* Copyright 2020-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2019-2023 the original author or authors.
|
||||
* Copyright 2019-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2023 the original author or authors.
|
||||
* Copyright 2013-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2014-2023 the original author or authors.
|
||||
* Copyright 2014-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -16,11 +16,9 @@
|
||||
package org.springframework.data.elasticsearch.annotations;
|
||||
|
||||
/**
|
||||
* Values based on <a href="https://www.elastic.co/guide/reference/mapping/date-format/">Elasticsearch reference
|
||||
* documentation</a>. The patterns are taken from this documentation and slightly adapted so that a Java
|
||||
* {@link java.time.format.DateTimeFormatter} produces the same values as the Elasticsearch formatter. Use
|
||||
* <code>format = {}</code> to disable built-in date formats in the {@link Field} annotation. If you want to use only a
|
||||
* custom date format pattern, you must set the <code>format</code> property to empty <code>{}</code>.
|
||||
* Values based on reference doc - https://www.elastic.co/guide/reference/mapping/date-format/. The patterns are taken
|
||||
* from this documentation and slightly adapted so that a Java {@link java.time.format.DateTimeFormatter} produces the
|
||||
* same values as the Elasticsearch formatter.
|
||||
*
|
||||
* @author Jakub Vavrik
|
||||
* @author Tim te Beek
|
||||
@@ -28,6 +26,19 @@ package org.springframework.data.elasticsearch.annotations;
|
||||
* @author Sascha Woo
|
||||
*/
|
||||
public enum DateFormat {
|
||||
/**
|
||||
* @deprecated since 4.2, will be removed in a future version. Use <code>format = {}</code> to disable built-in date
|
||||
* formats in the @Field annotation.
|
||||
*/
|
||||
@Deprecated
|
||||
none(""), //
|
||||
/**
|
||||
* @deprecated since 4.2, will be removed in a future version.It is no longer required for using a custom date format
|
||||
* pattern. If you want to use only a custom date format pattern, you must set the <code>format</code>
|
||||
* property to empty <code>{}</code>.
|
||||
*/
|
||||
@Deprecated
|
||||
custom(""), //
|
||||
basic_date("uuuuMMdd"), //
|
||||
basic_date_time("uuuuMMdd'T'HHmmss.SSSXXX"), //
|
||||
basic_date_time_no_millis("uuuuMMdd'T'HHmmssXXX"), //
|
||||
@@ -49,7 +60,7 @@ public enum DateFormat {
|
||||
date_hour_minute_second_millis("uuuu-MM-dd'T'HH:mm:ss.SSS"), //
|
||||
date_optional_time("uuuu-MM-dd['T'HH:mm:ss.SSSXXX]"), //
|
||||
date_time("uuuu-MM-dd'T'HH:mm:ss.SSSXXX"), //
|
||||
date_time_no_millis("uuuu-MM-dd'T'HH:mm:ssVV"), // here Elasticsearch uses the zone-id in its implementation
|
||||
date_time_no_millis("uuuu-MM-dd'T'HH:mm:ssVV"), // here Elasticsearch uses the zone-id in it's implementation
|
||||
epoch_millis("epoch_millis"), //
|
||||
epoch_second("epoch_second"), //
|
||||
hour("HH"), //
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2023 the original author or authors.
|
||||
* Copyright 2013-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -53,6 +53,49 @@ public @interface Document {
|
||||
*/
|
||||
String indexName();
|
||||
|
||||
/**
|
||||
* Use server-side settings when creating the index.
|
||||
*
|
||||
* @deprecated since 4.2, use the {@link Setting} annotation to configure settings
|
||||
*/
|
||||
@Deprecated
|
||||
boolean useServerConfiguration() default false;
|
||||
|
||||
/**
|
||||
* Number of shards for the index {@link #indexName()}. Used for index creation. <br/>
|
||||
* With version 4.0, the default value is changed from 5 to 1 to reflect the change in the default settings of
|
||||
* Elasticsearch which changed to 1 as well in Elasticsearch 7.0.
|
||||
* ComposableAnnotationsUnitTest.documentAnnotationShouldBeComposable:60
|
||||
*
|
||||
* @deprecated since 4.2, use the {@link Setting} annotation to configure settings
|
||||
*/
|
||||
@Deprecated
|
||||
short shards() default 1;
|
||||
|
||||
/**
|
||||
* Number of replicas for the index {@link #indexName()}. Used for index creation.
|
||||
*
|
||||
* @deprecated since 4.2, use the {@link Setting} annotation to configure settings
|
||||
*/
|
||||
@Deprecated
|
||||
short replicas() default 1;
|
||||
|
||||
/**
|
||||
* Refresh interval for the index {@link #indexName()}. Used for index creation.
|
||||
*
|
||||
* @deprecated since 4.2, use the {@link Setting} annotation to configure settings
|
||||
*/
|
||||
@Deprecated
|
||||
String refreshInterval() default "1s";
|
||||
|
||||
/**
|
||||
* Index storage type for the index {@link #indexName()}. Used for index creation.
|
||||
*
|
||||
* @deprecated since 4.2, use the {@link Setting} annotation to configure settings
|
||||
*/
|
||||
@Deprecated
|
||||
String indexStoreType() default "fs";
|
||||
|
||||
/**
|
||||
* Configuration whether to create an index on repository bootstrapping.
|
||||
*/
|
||||
@@ -77,22 +120,6 @@ public @interface Document {
|
||||
*/
|
||||
Dynamic dynamic() default Dynamic.INHERIT;
|
||||
|
||||
/**
|
||||
* Specifies if the id property should also be stored in the Elasticsearch document source. Default value is
|
||||
* {@literal true}
|
||||
*
|
||||
* @since 5.1
|
||||
*/
|
||||
boolean storeIdInSource() default true;
|
||||
|
||||
/**
|
||||
* Specifies if the version property should also be stored in the Elasticsearch document source. Default value is
|
||||
* true.
|
||||
*
|
||||
* @since 5.1
|
||||
*/
|
||||
boolean storeVersionInSource() default true;
|
||||
|
||||
/**
|
||||
* @since 4.3
|
||||
*/
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -46,7 +46,7 @@ public enum Dynamic {
|
||||
/**
|
||||
* Inherit the dynamic setting from their parent object or from the mapping type.
|
||||
*/
|
||||
INHERIT("inherit");
|
||||
INHERIT("nherit");
|
||||
|
||||
private final String mappedName;
|
||||
|
||||
|
||||
+11
-6
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2022-2023 the original author or authors.
|
||||
* Copyright 2019-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -22,14 +22,19 @@ import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Annotation to mark a property that will be written to Elasticsearch, but not set when reading from Elasticsearch.
|
||||
* This is needed for synthesized fields that may be used for search but that are not available in the entity.
|
||||
* Annotation to set the dynamic mapping mode
|
||||
* {@see <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/dynamic.html">elasticsearch doc</a>}
|
||||
*
|
||||
* @author Peter-Josef Meisch
|
||||
* @since 5.0
|
||||
* @author Sascha Woo
|
||||
* @since 4.0
|
||||
* @deprecated since 4.3, use {@link Document#dynamic()} or {@link Field#dynamic()} instead.
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ ElementType.METHOD, ElementType.FIELD })
|
||||
@Target({ ElementType.TYPE, ElementType.FIELD })
|
||||
@Documented
|
||||
public @interface WriteOnlyProperty {
|
||||
@Deprecated
|
||||
public @interface DynamicMapping {
|
||||
|
||||
DynamicMappingValue value() default DynamicMappingValue.True;
|
||||
}
|
||||
+16
-12
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2023 the original author or authors.
|
||||
* Copyright 2019-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -13,23 +13,27 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.core.query;
|
||||
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.Assert;
|
||||
package org.springframework.data.elasticsearch.annotations;
|
||||
|
||||
/**
|
||||
* Record defining a docvalue_field to be used in a query.
|
||||
* values for the {@link DynamicMapping annotation}
|
||||
*
|
||||
* @author Peter-Josef Meisch
|
||||
* @since 5.1
|
||||
* @author Sascha Woo
|
||||
* @since 4.0
|
||||
* @deprecated since 4.3, use {@link Document#dynamic()} or {@link Field#dynamic()} instead.
|
||||
*/
|
||||
public record DocValueField(String field, @Nullable String format) {
|
||||
public DocValueField {
|
||||
Assert.notNull(field, "field must not be null");
|
||||
@Deprecated
|
||||
public enum DynamicMappingValue {
|
||||
True("true"), False("false"), Strict("strict");
|
||||
|
||||
private final String mappedName;
|
||||
|
||||
DynamicMappingValue(String mappedName) {
|
||||
this.mappedName = mappedName;
|
||||
}
|
||||
|
||||
public DocValueField(String field) {
|
||||
this(field, null);
|
||||
public String getMappedName() {
|
||||
return mappedName;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2023 the original author or authors.
|
||||
* Copyright 2013-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -39,7 +39,7 @@ import org.springframework.core.annotation.AliasFor;
|
||||
* @author Sascha Woo
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.METHOD })
|
||||
@Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE })
|
||||
@Documented
|
||||
@Inherited
|
||||
public @interface Field {
|
||||
@@ -53,8 +53,9 @@ public @interface Field {
|
||||
String value() default "";
|
||||
|
||||
/**
|
||||
* The <em>name</em> to be used to store the field inside the document. If not set, the name of the annotated property
|
||||
* is used.
|
||||
* The <em>name</em> to be used to store the field inside the document.
|
||||
* <p>
|
||||
* √5 If not set, the name of the annotated property is used.
|
||||
*
|
||||
* @since 3.2
|
||||
*/
|
||||
@@ -140,7 +141,7 @@ public @interface Field {
|
||||
/**
|
||||
* @since 4.0
|
||||
*/
|
||||
String similarity() default Similarity.Default;
|
||||
Similarity similarity() default Similarity.Default;
|
||||
|
||||
/**
|
||||
* @since 4.0
|
||||
@@ -210,12 +211,4 @@ public @interface Field {
|
||||
* @since 4.3
|
||||
*/
|
||||
boolean excludeFromSource() default false;
|
||||
|
||||
/**
|
||||
* when this field is a {{@link String}}, a {{@link java.util.Collection}} or a {{@link java.util.Map}} that is empty
|
||||
* this property controlls whether the empty value is sent to Elasticsearch.
|
||||
*
|
||||
* @since 5.1
|
||||
*/
|
||||
boolean storeEmptyValue() default true;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2023 the original author or authors.
|
||||
* Copyright 2013-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2023 the original author or authors.
|
||||
* Copyright 2013-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2017-2023 the original author or authors.
|
||||
* Copyright 2017-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2020-2023 the original author or authors.
|
||||
* Copyright 2020-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2020-2023 the original author or authors.
|
||||
* Copyright 2020-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2020-2023 the original author or authors.
|
||||
* Copyright 2020-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2019-2023 the original author or authors.
|
||||
* Copyright 2019-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2019-2023 the original author or authors.
|
||||
* Copyright 2019-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
-42
@@ -1,42 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.annotations;
|
||||
|
||||
import org.springframework.data.annotation.ReadOnlyProperty;
|
||||
import org.springframework.data.annotation.Transient;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Annotation to mark a String property of an entity to be filled with the name of the index where the entity was
|
||||
* stored after it is indexed into Elasticsearch. This can be used when the name of the index is dynamically created
|
||||
* or when a document was indexed into a write alias.
|
||||
*
|
||||
* This can not be used to specify the index where an entity should be written to.
|
||||
*
|
||||
* @author Peter-Josef Meisch
|
||||
* @since 5.1
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE })
|
||||
@Documented
|
||||
@Field(type = FieldType.Auto) // prevents the property being written to the index mapping
|
||||
public @interface IndexedIndexName {
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2014-2023 the original author or authors.
|
||||
* Copyright 2014-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -109,7 +109,7 @@ public @interface InnerField {
|
||||
/**
|
||||
* @since 4.0
|
||||
*/
|
||||
String similarity() default Similarity.Default;
|
||||
Similarity similarity() default Similarity.Default;
|
||||
|
||||
/**
|
||||
* @since 4.0
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2020-2023 the original author or authors.
|
||||
* Copyright 2020-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2020-2023 the original author or authors.
|
||||
* Copyright 2020-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2014-2023 the original author or authors.
|
||||
* Copyright 2014-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2014-2023 the original author or authors.
|
||||
* Copyright 2014-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2020-2023 the original author or authors.
|
||||
* Copyright 2020-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2023 the original author or authors.
|
||||
* Copyright 2013-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -15,14 +15,8 @@
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.annotations;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import org.springframework.core.annotation.AliasFor;
|
||||
import org.springframework.data.annotation.QueryAnnotation;
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* Query
|
||||
@@ -40,17 +34,16 @@ import org.springframework.data.annotation.QueryAnnotation;
|
||||
public @interface Query {
|
||||
|
||||
/**
|
||||
* @return Elasticsearch query to be used when executing query. May contain placeholders eg. ?0. Alias for query.
|
||||
* @return Elasticsearch query to be used when executing query. May contain placeholders eg. ?0
|
||||
*/
|
||||
@AliasFor("query")
|
||||
String value() default "";
|
||||
|
||||
/**
|
||||
* @return Elasticsearch query to be used when executing query. May contain placeholders eg. ?0. Alias for value
|
||||
* @since 5.0
|
||||
* Named Query Named looked up by repository.
|
||||
*
|
||||
* @deprecated since 4.2, not implemented and used anywhere
|
||||
*/
|
||||
@AliasFor("value")
|
||||
String query() default "";
|
||||
String name() default "";
|
||||
|
||||
/**
|
||||
* Returns whether the query defined should be executed as count projection.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2014-2023 the original author or authors.
|
||||
* Copyright 2014-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2019-2023 the original author or authors.
|
||||
* Copyright 2019-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -19,9 +19,18 @@ package org.springframework.data.elasticsearch.annotations;
|
||||
* @author Peter-Josef Meisch
|
||||
* @since 4.0
|
||||
*/
|
||||
public final class Similarity {
|
||||
public final static String Default = "default";
|
||||
public final static String BM25 = "BM25";
|
||||
public final static String classic = "classic";
|
||||
public final static String Boolean = "boolean";
|
||||
public enum Similarity {
|
||||
Default("default"), BM25("BM25"), classic("classic"), Boolean("boolean");
|
||||
|
||||
// need to use a custom name because 'boolean' can't be used as enum name
|
||||
private final String toStringName;
|
||||
|
||||
Similarity(String name) {
|
||||
this.toStringName = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return toStringName;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
/*
|
||||
* Copyright 2022-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.data.elasticsearch.annotations;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* This annotation can be placed on repository methods to define the properties that should be requested from
|
||||
* Elasticsearch when the method is run.
|
||||
*
|
||||
* @author Alexander Torres
|
||||
* @author Peter-Josef Meisch
|
||||
* @since 5.0
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
|
||||
@Documented
|
||||
public @interface SourceFilters {
|
||||
|
||||
/**
|
||||
* Properties to be requested from Elasticsearch to be included in the response. These can be passed in as literals
|
||||
* like
|
||||
*
|
||||
* <pre>
|
||||
* {@code @SourceFilters(includes = {"property1", "property2"})}
|
||||
* </pre>
|
||||
*
|
||||
* or as a parameterized value
|
||||
*
|
||||
* <pre>
|
||||
* {@code @SourceFilters(includes = "?0")}
|
||||
* </pre>
|
||||
*
|
||||
* when the list of properties is passed as a function parameter.
|
||||
*/
|
||||
String[] includes() default "";
|
||||
|
||||
/**
|
||||
* Properties to be requested from Elasticsearch to be excluded in the response. These can be passed in as literals
|
||||
* like
|
||||
*
|
||||
* <pre>
|
||||
* {@code @SourceFilters(excludes = {"property1", "property2"})}
|
||||
* </pre>
|
||||
*
|
||||
* or as a parameterized value
|
||||
*
|
||||
* <pre>
|
||||
* {@code @SourceFilters(excludes = "?0")}
|
||||
* </pre>
|
||||
*
|
||||
* when the list of properties is passed as a function parameter.
|
||||
*/
|
||||
String[] excludes() default "";
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2019-2023 the original author or authors.
|
||||
* Copyright 2019-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.aot;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import org.springframework.data.util.ReactiveWrappers;
|
||||
|
||||
/**
|
||||
* @author Peter-Josef Meisch
|
||||
* @since 5.1
|
||||
*/
|
||||
public class ElasticsearchAotPredicates {
|
||||
|
||||
public static final Predicate<ReactiveWrappers.ReactiveLibrary> IS_REACTIVE_LIBARARY_AVAILABLE = (
|
||||
lib) -> ReactiveWrappers.isAvailable(lib);
|
||||
|
||||
public static boolean isReactorPresent() {
|
||||
return IS_REACTIVE_LIBARARY_AVAILABLE.test(ReactiveWrappers.ReactiveLibrary.PROJECT_REACTOR);
|
||||
}
|
||||
|
||||
}
|
||||
-75
@@ -1,75 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.aot;
|
||||
|
||||
import static org.springframework.data.elasticsearch.aot.ElasticsearchAotPredicates.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.springframework.aot.hint.MemberCategory;
|
||||
import org.springframework.aot.hint.RuntimeHints;
|
||||
import org.springframework.aot.hint.RuntimeHintsRegistrar;
|
||||
import org.springframework.aot.hint.TypeReference;
|
||||
import org.springframework.data.elasticsearch.client.elc.EntityAsMap;
|
||||
import org.springframework.data.elasticsearch.core.event.AfterConvertCallback;
|
||||
import org.springframework.data.elasticsearch.core.event.AfterLoadCallback;
|
||||
import org.springframework.data.elasticsearch.core.event.AfterSaveCallback;
|
||||
import org.springframework.data.elasticsearch.core.event.AuditingEntityCallback;
|
||||
import org.springframework.data.elasticsearch.core.event.BeforeConvertCallback;
|
||||
import org.springframework.data.elasticsearch.core.event.ReactiveAfterConvertCallback;
|
||||
import org.springframework.data.elasticsearch.core.event.ReactiveAfterLoadCallback;
|
||||
import org.springframework.data.elasticsearch.core.event.ReactiveAfterSaveCallback;
|
||||
import org.springframework.data.elasticsearch.core.event.ReactiveAuditingEntityCallback;
|
||||
import org.springframework.data.elasticsearch.core.event.ReactiveBeforeConvertCallback;
|
||||
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
|
||||
import org.springframework.lang.Nullable;
|
||||
|
||||
/**
|
||||
* @author Peter-Josef Meisch
|
||||
* @since 5.1
|
||||
*/
|
||||
public class ElasticsearchRuntimeHints implements RuntimeHintsRegistrar {
|
||||
|
||||
@Override
|
||||
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
|
||||
hints.reflection().registerTypes( //
|
||||
Arrays.asList( //
|
||||
TypeReference.of(AfterConvertCallback.class), //
|
||||
TypeReference.of(AfterLoadCallback.class), //
|
||||
TypeReference.of(AfterSaveCallback.class), //
|
||||
TypeReference.of(BeforeConvertCallback.class), //
|
||||
TypeReference.of(EntityAsMap.class) //
|
||||
), //
|
||||
builder -> builder.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
|
||||
MemberCategory.INVOKE_PUBLIC_METHODS));
|
||||
|
||||
if (isReactorPresent()) {
|
||||
hints.reflection().registerTypes( //
|
||||
Arrays.asList( //
|
||||
TypeReference.of(ReactiveAfterConvertCallback.class), //
|
||||
TypeReference.of(ReactiveAfterLoadCallback.class), //
|
||||
TypeReference.of(ReactiveAfterSaveCallback.class), //
|
||||
TypeReference.of(ReactiveBeforeConvertCallback.class) //
|
||||
), //
|
||||
builder -> builder.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
|
||||
MemberCategory.INVOKE_PUBLIC_METHODS));
|
||||
}
|
||||
|
||||
// properties needed to log the different versions
|
||||
hints.resources().registerPattern("versions.properties");
|
||||
hints.resources().registerPattern("co/elastic/clients/version.properties");
|
||||
}
|
||||
}
|
||||
+49
-21
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2018-2023 the original author or authors.
|
||||
* Copyright 2018-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -20,13 +20,17 @@ import java.net.SocketAddress;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.SSLContext;
|
||||
|
||||
import org.springframework.data.elasticsearch.support.HttpHeaders;
|
||||
import org.elasticsearch.client.RestClientBuilder.HttpClientConfigCallback;
|
||||
import org.springframework.data.elasticsearch.client.reactive.ReactiveRestClients;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
|
||||
/**
|
||||
* Configuration interface exposing common client configuration properties for Elasticsearch clients.
|
||||
@@ -50,6 +54,7 @@ public interface ClientConfiguration {
|
||||
|
||||
/**
|
||||
* Creates a new {@link ClientConfiguration} instance configured to localhost.
|
||||
* <p/>
|
||||
*
|
||||
* <pre class="code">
|
||||
* // "localhost:9200"
|
||||
@@ -64,8 +69,9 @@ public interface ClientConfiguration {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new {@link ClientConfiguration} instance configured to a single host given {@code hostAndPort}. For
|
||||
* example given the endpoint http://localhost:9200
|
||||
* Creates a new {@link ClientConfiguration} instance configured to a single host given {@code hostAndPort}.
|
||||
* <p/>
|
||||
* For example given the endpoint http://localhost:9200
|
||||
*
|
||||
* <pre class="code">
|
||||
* ClientConfiguration configuration = ClientConfiguration.create("localhost:9200");
|
||||
@@ -78,8 +84,9 @@ public interface ClientConfiguration {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new {@link ClientConfiguration} instance configured to a single host given {@link InetSocketAddress}. For
|
||||
* example given the endpoint http://localhost:9200
|
||||
* Creates a new {@link ClientConfiguration} instance configured to a single host given {@link InetSocketAddress}.
|
||||
* <p/>
|
||||
* For example given the endpoint http://localhost:9200
|
||||
*
|
||||
* <pre class="code">
|
||||
* ClientConfiguration configuration = ClientConfiguration
|
||||
@@ -120,12 +127,6 @@ public interface ClientConfiguration {
|
||||
*/
|
||||
Optional<SSLContext> getSslContext();
|
||||
|
||||
/**
|
||||
* @return the optional SHA-256 fingerprint of the self-signed http_ca.crt certificate output by Elasticsearch at
|
||||
* startup time.
|
||||
*/
|
||||
Optional<String> getCaFingerprint();
|
||||
|
||||
/**
|
||||
* Returns the {@link HostnameVerifier} to use. Can be {@link Optional#empty()} if not configured.
|
||||
*
|
||||
@@ -167,6 +168,19 @@ public interface ClientConfiguration {
|
||||
*/
|
||||
Optional<String> getProxy();
|
||||
|
||||
/**
|
||||
* @return the function for configuring a WebClient.
|
||||
*/
|
||||
Function<WebClient, WebClient> getWebClientConfigurer();
|
||||
|
||||
/**
|
||||
* @return the Rest Client configuration callback.
|
||||
* @since 4.2
|
||||
* @deprecated since 4.3 use {@link #getClientConfigurers()}
|
||||
*/
|
||||
@Deprecated
|
||||
HttpClientConfigCallback getHttpClientConfigurer();
|
||||
|
||||
/**
|
||||
* @return the client configuration callbacks
|
||||
* @since 4.3
|
||||
@@ -254,15 +268,6 @@ public interface ClientConfiguration {
|
||||
* @return the {@link TerminalClientConfigurationBuilder}.
|
||||
*/
|
||||
TerminalClientConfigurationBuilder usingSsl(SSLContext sslContext, HostnameVerifier hostnameVerifier);
|
||||
|
||||
/**
|
||||
* Connect via https using a SSLContext that is build from the given certificate fingerprint.
|
||||
*
|
||||
* @param caFingerprint the SHA-256 fingerprint of the self-signed http_ca.crt certificate output by Elasticsearch
|
||||
* at startup time.
|
||||
* @return the {@link TerminalClientConfigurationBuilder}.
|
||||
*/
|
||||
TerminalClientConfigurationBuilder usingSsl(String caFingerprint);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -344,6 +349,29 @@ public interface ClientConfiguration {
|
||||
*/
|
||||
TerminalClientConfigurationBuilder withProxy(String proxy);
|
||||
|
||||
/**
|
||||
* set customization hook in case of a reactive configuration
|
||||
*
|
||||
* @param webClientConfigurer function to configure the WebClient
|
||||
* @return the {@link TerminalClientConfigurationBuilder}.
|
||||
* @deprecated since 4.3, use {@link #withClientConfigurer(ClientConfigurationCallback)} with
|
||||
* {@link ReactiveRestClients.WebClientConfigurationCallback}
|
||||
*/
|
||||
@Deprecated
|
||||
TerminalClientConfigurationBuilder withWebClientConfigurer(Function<WebClient, WebClient> webClientConfigurer);
|
||||
|
||||
/**
|
||||
* Register a {HttpClientConfigCallback} to configure the non-reactive REST client.
|
||||
*
|
||||
* @param httpClientConfigurer configuration callback, must not be null.
|
||||
* @return the {@link TerminalClientConfigurationBuilder}.
|
||||
* @since 4.2
|
||||
* @deprecated since 4.3, use {@link #withClientConfigurer(ClientConfigurationCallback)} with
|
||||
* {@link RestClients.RestClientConfigurationCallback}
|
||||
*/
|
||||
@Deprecated
|
||||
TerminalClientConfigurationBuilder withHttpClientConfigurer(HttpClientConfigCallback httpClientConfigurer);
|
||||
|
||||
/**
|
||||
* Register a {@link ClientConfigurationCallback} to configure the client.
|
||||
*
|
||||
|
||||
+48
-33
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2018-2023 the original author or authors.
|
||||
* Copyright 2018-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -20,7 +20,9 @@ import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.SSLContext;
|
||||
@@ -29,9 +31,11 @@ import org.elasticsearch.client.RestClientBuilder.HttpClientConfigCallback;
|
||||
import org.springframework.data.elasticsearch.client.ClientConfiguration.ClientConfigurationBuilderWithRequiredEndpoint;
|
||||
import org.springframework.data.elasticsearch.client.ClientConfiguration.MaybeSecureClientConfigurationBuilder;
|
||||
import org.springframework.data.elasticsearch.client.ClientConfiguration.TerminalClientConfigurationBuilder;
|
||||
import org.springframework.data.elasticsearch.support.HttpHeaders;
|
||||
import org.springframework.data.elasticsearch.client.reactive.ReactiveRestClients;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
|
||||
/**
|
||||
* Default builder implementation for {@link ClientConfiguration}.
|
||||
@@ -47,20 +51,20 @@ class ClientConfigurationBuilder
|
||||
implements ClientConfigurationBuilderWithRequiredEndpoint, MaybeSecureClientConfigurationBuilder {
|
||||
|
||||
private final List<InetSocketAddress> hosts = new ArrayList<>();
|
||||
private HttpHeaders headers = new HttpHeaders();
|
||||
private HttpHeaders headers = HttpHeaders.EMPTY;
|
||||
private boolean useSsl;
|
||||
@Nullable private SSLContext sslContext;
|
||||
@Nullable private String caFingerprint;
|
||||
@Nullable private HostnameVerifier hostnameVerifier;
|
||||
private @Nullable SSLContext sslContext;
|
||||
private @Nullable HostnameVerifier hostnameVerifier;
|
||||
private Duration connectTimeout = Duration.ofSeconds(10);
|
||||
private Duration soTimeout = Duration.ofSeconds(5);
|
||||
@Nullable private String username;
|
||||
@Nullable private String password;
|
||||
@Nullable private String pathPrefix;
|
||||
@Nullable private String proxy;
|
||||
private Supplier<HttpHeaders> headersSupplier = HttpHeaders::new;
|
||||
@Deprecated private final HttpClientConfigCallback httpClientConfigurer = httpClientBuilder -> httpClientBuilder;
|
||||
private final List<ClientConfiguration.ClientConfigurationCallback<?>> clientConfigurers = new ArrayList<>();
|
||||
private @Nullable String username;
|
||||
private @Nullable String password;
|
||||
private @Nullable String pathPrefix;
|
||||
private @Nullable String proxy;
|
||||
private Function<WebClient, WebClient> webClientConfigurer = Function.identity();
|
||||
private Supplier<HttpHeaders> headersSupplier = () -> HttpHeaders.EMPTY;
|
||||
@Deprecated private HttpClientConfigCallback httpClientConfigurer = httpClientBuilder -> httpClientBuilder;
|
||||
private List<ClientConfiguration.ClientConfigurationCallback<?>> clientConfigurers = new ArrayList<>();
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
@@ -71,7 +75,7 @@ class ClientConfigurationBuilder
|
||||
|
||||
Assert.notEmpty(hostAndPorts, "At least one host is required");
|
||||
|
||||
this.hosts.addAll(Arrays.stream(hostAndPorts).map(ClientConfigurationBuilder::parse).toList());
|
||||
this.hosts.addAll(Arrays.stream(hostAndPorts).map(ClientConfigurationBuilder::parse).collect(Collectors.toList()));
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -137,20 +141,10 @@ class ClientConfigurationBuilder
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TerminalClientConfigurationBuilder usingSsl(String caFingerprint) {
|
||||
|
||||
Assert.notNull(caFingerprint, "caFingerprint must not be null");
|
||||
|
||||
this.useSsl = true;
|
||||
this.caFingerprint = caFingerprint;
|
||||
return this;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.elasticsearch.client.ClientConfiguration.TerminalClientConfigurationBuilder#withDefaultHeaders(org.springframework.http.HttpHeaders)
|
||||
*/
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.elasticsearch.client.ClientConfiguration.TerminalClientConfigurationBuilder#withDefaultHeaders(org.springframework.http.HttpHeaders)
|
||||
*/
|
||||
@Override
|
||||
public TerminalClientConfigurationBuilder withDefaultHeaders(HttpHeaders defaultHeaders) {
|
||||
|
||||
@@ -207,6 +201,28 @@ class ClientConfigurationBuilder
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TerminalClientConfigurationBuilder withWebClientConfigurer(
|
||||
Function<WebClient, WebClient> webClientConfigurer) {
|
||||
|
||||
Assert.notNull(webClientConfigurer, "webClientConfigurer must not be null");
|
||||
|
||||
this.webClientConfigurer = webClientConfigurer;
|
||||
this.clientConfigurers.add(ReactiveRestClients.WebClientConfigurationCallback.from(webClientConfigurer));
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TerminalClientConfigurationBuilder withHttpClientConfigurer(HttpClientConfigCallback httpClientConfigurer) {
|
||||
|
||||
Assert.notNull(httpClientConfigurer, "httpClientConfigurer must not be null");
|
||||
|
||||
this.httpClientConfigurer = httpClientConfigurer;
|
||||
this.clientConfigurers
|
||||
.add(RestClients.RestClientConfigurationCallback.from(httpClientConfigurer::customizeHttpClient));
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TerminalClientConfigurationBuilder withClientConfigurer(
|
||||
ClientConfiguration.ClientConfigurationCallback<?> clientConfigurer) {
|
||||
@@ -234,15 +250,14 @@ class ClientConfigurationBuilder
|
||||
public ClientConfiguration build() {
|
||||
|
||||
if (username != null && password != null) {
|
||||
if (HttpHeaders.EMPTY.equals(headers)) {
|
||||
headers = new HttpHeaders();
|
||||
}
|
||||
headers.setBasicAuth(username, password);
|
||||
}
|
||||
|
||||
if (sslContext != null && caFingerprint != null) {
|
||||
throw new IllegalArgumentException("Either SSLContext or caFingerprint must be set, but not both");
|
||||
}
|
||||
|
||||
return new DefaultClientConfiguration(hosts, headers, useSsl, sslContext, caFingerprint, soTimeout, connectTimeout,
|
||||
pathPrefix, hostnameVerifier, proxy, httpClientConfigurer, clientConfigurers, headersSupplier);
|
||||
return new DefaultClientConfiguration(hosts, headers, useSsl, sslContext, soTimeout, connectTimeout, pathPrefix,
|
||||
hostnameVerifier, proxy, webClientConfigurer, httpClientConfigurer, clientConfigurers, headersSupplier);
|
||||
}
|
||||
|
||||
private static InetSocketAddress parse(String hostAndPort) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2018-2023 the original author or authors.
|
||||
* Copyright 2018-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -19,6 +19,7 @@ import java.util.function.Supplier;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
|
||||
@@ -29,11 +30,8 @@ import org.springframework.util.ObjectUtils;
|
||||
* @author Mark Paluch
|
||||
* @author Christoph Strobl
|
||||
* @author Peter-Josef Meisch
|
||||
* @author Oliver Drotbohm
|
||||
* @since 3.2
|
||||
* @deprecated since 5.0, Elasticsearch's RestClient has a trace level logging available.
|
||||
*/
|
||||
@Deprecated
|
||||
public abstract class ClientLogger {
|
||||
|
||||
private static final Log WIRE_LOGGER = LogFactory.getLog("org.springframework.data.elasticsearch.client.WIRE");
|
||||
@@ -127,10 +125,10 @@ public abstract class ClientLogger {
|
||||
* @param logId the correlation id, see {@link #newLogId()}.
|
||||
* @param statusCode the HTTP status code.
|
||||
*/
|
||||
public static void logRawResponse(String logId, @Nullable Integer statusCode) {
|
||||
public static void logRawResponse(String logId, @Nullable HttpStatus statusCode) {
|
||||
|
||||
if (isEnabled()) {
|
||||
WIRE_LOGGER.trace(String.format("[%s] Received raw response: %d", logId, statusCode));
|
||||
WIRE_LOGGER.trace(String.format("[%s] Received raw response: %s", logId, statusCode));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,10 +139,10 @@ public abstract class ClientLogger {
|
||||
* @param statusCode the HTTP status code.
|
||||
* @param headers a String containing the headers
|
||||
*/
|
||||
public static void logRawResponse(String logId, @Nullable Integer statusCode, String headers) {
|
||||
public static void logRawResponse(String logId, @Nullable HttpStatus statusCode, String headers) {
|
||||
|
||||
if (isEnabled()) {
|
||||
WIRE_LOGGER.trace(String.format("[%s] Received response: %d%n%s", logId, statusCode, headers));
|
||||
WIRE_LOGGER.trace(String.format("[%s] Received response: %s%n%s", logId, statusCode, headers));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,10 +153,10 @@ public abstract class ClientLogger {
|
||||
* @param statusCode the HTTP status code.
|
||||
* @param body body content.
|
||||
*/
|
||||
public static void logResponse(String logId, Integer statusCode, String body) {
|
||||
public static void logResponse(String logId, HttpStatus statusCode, String body) {
|
||||
|
||||
if (isEnabled()) {
|
||||
WIRE_LOGGER.trace(String.format("[%s] Received response: %d%nResponse body: %s", logId, statusCode, body));
|
||||
WIRE_LOGGER.trace(String.format("[%s] Received response: %s%nResponse body: %s", logId, statusCode, body));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,10 +169,10 @@ public abstract class ClientLogger {
|
||||
* @param body body content.
|
||||
* @since 4.4
|
||||
*/
|
||||
public static void logResponse(String logId, @Nullable Integer statusCode, String headers, String body) {
|
||||
public static void logResponse(String logId, @Nullable HttpStatus statusCode, String headers, String body) {
|
||||
|
||||
if (isEnabled()) {
|
||||
WIRE_LOGGER.trace(String.format("[%s] Received response: %d%nHeaders: %s%nResponse body: %s", logId, statusCode,
|
||||
WIRE_LOGGER.trace(String.format("[%s] Received response: %s%nHeaders: %s%nResponse body: %s", logId, statusCode,
|
||||
headers, body));
|
||||
}
|
||||
}
|
||||
|
||||
+30
-19
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2018-2023 the original author or authors.
|
||||
* Copyright 2018-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -17,16 +17,20 @@ package org.springframework.data.elasticsearch.client;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.SSLContext;
|
||||
|
||||
import org.elasticsearch.client.RestClientBuilder.HttpClientConfigCallback;
|
||||
import org.springframework.data.elasticsearch.support.HttpHeaders;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
|
||||
/**
|
||||
* Default {@link ClientConfiguration} implementation.
|
||||
@@ -42,33 +46,33 @@ class DefaultClientConfiguration implements ClientConfiguration {
|
||||
private final List<InetSocketAddress> hosts;
|
||||
private final HttpHeaders headers;
|
||||
private final boolean useSsl;
|
||||
@Nullable private final SSLContext sslContext;
|
||||
@Nullable private final String caFingerprint;
|
||||
private final @Nullable SSLContext sslContext;
|
||||
private final Duration soTimeout;
|
||||
private final Duration connectTimeout;
|
||||
@Nullable private final String pathPrefix;
|
||||
@Nullable private final HostnameVerifier hostnameVerifier;
|
||||
@Nullable private final String proxy;
|
||||
private final @Nullable String pathPrefix;
|
||||
private final @Nullable HostnameVerifier hostnameVerifier;
|
||||
private final @Nullable String proxy;
|
||||
private final Function<WebClient, WebClient> webClientConfigurer;
|
||||
private final HttpClientConfigCallback httpClientConfigurer;
|
||||
private final Supplier<HttpHeaders> headersSupplier;
|
||||
private final List<ClientConfigurationCallback<?>> clientConfigurers;
|
||||
|
||||
DefaultClientConfiguration(List<InetSocketAddress> hosts, HttpHeaders headers, boolean useSsl,
|
||||
@Nullable SSLContext sslContext, @Nullable String caFingerprint, Duration soTimeout, Duration connectTimeout,
|
||||
@Nullable String pathPrefix, @Nullable HostnameVerifier hostnameVerifier, @Nullable String proxy,
|
||||
HttpClientConfigCallback httpClientConfigurer, List<ClientConfigurationCallback<?>> clientConfigurers,
|
||||
Supplier<HttpHeaders> headersSupplier) {
|
||||
@Nullable SSLContext sslContext, Duration soTimeout, Duration connectTimeout, @Nullable String pathPrefix,
|
||||
@Nullable HostnameVerifier hostnameVerifier, @Nullable String proxy,
|
||||
Function<WebClient, WebClient> webClientConfigurer, HttpClientConfigCallback httpClientConfigurer,
|
||||
List<ClientConfigurationCallback<?>> clientConfigurers, Supplier<HttpHeaders> headersSupplier) {
|
||||
|
||||
this.hosts = List.copyOf(hosts);
|
||||
this.headers = headers;
|
||||
this.hosts = Collections.unmodifiableList(new ArrayList<>(hosts));
|
||||
this.headers = new HttpHeaders(headers);
|
||||
this.useSsl = useSsl;
|
||||
this.sslContext = sslContext;
|
||||
this.caFingerprint = caFingerprint;
|
||||
this.soTimeout = soTimeout;
|
||||
this.connectTimeout = connectTimeout;
|
||||
this.pathPrefix = pathPrefix;
|
||||
this.hostnameVerifier = hostnameVerifier;
|
||||
this.proxy = proxy;
|
||||
this.webClientConfigurer = webClientConfigurer;
|
||||
this.httpClientConfigurer = httpClientConfigurer;
|
||||
this.clientConfigurers = clientConfigurers;
|
||||
this.headersSupplier = headersSupplier;
|
||||
@@ -94,11 +98,6 @@ class DefaultClientConfiguration implements ClientConfiguration {
|
||||
return Optional.ofNullable(this.sslContext);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> getCaFingerprint() {
|
||||
return Optional.ofNullable(this.caFingerprint);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<HostnameVerifier> getHostNameVerifier() {
|
||||
return Optional.ofNullable(this.hostnameVerifier);
|
||||
@@ -125,6 +124,18 @@ class DefaultClientConfiguration implements ClientConfiguration {
|
||||
return Optional.ofNullable(proxy);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Function<WebClient, WebClient> getWebClientConfigurer() {
|
||||
return webClientConfigurer;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@Override
|
||||
public HttpClientConfigCallback getHttpClientConfigurer() {
|
||||
return httpClientConfigurer;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public <T> List<ClientConfigurationCallback<?>> getClientConfigurers() {
|
||||
return clientConfigurers;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2018-2023 the original author or authors.
|
||||
* Copyright 2018-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2018-2023 the original author or authors.
|
||||
* Copyright 2018-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -26,7 +26,7 @@ import org.springframework.util.StringUtils;
|
||||
* @author Mark Paluch
|
||||
* @since 3.2
|
||||
*/
|
||||
public class InetSocketAddressParser {
|
||||
class InetSocketAddressParser {
|
||||
|
||||
/**
|
||||
* Parse a host and port string into a {@link InetSocketAddress}.
|
||||
@@ -36,7 +36,7 @@ public class InetSocketAddressParser {
|
||||
* @return a {@link InetSocketAddress} that is unresolved to avoid DNS lookups.
|
||||
* @see InetSocketAddress#createUnresolved(String, int)
|
||||
*/
|
||||
public static InetSocketAddress parse(String hostPortString, int defaultPort) {
|
||||
static InetSocketAddress parse(String hostPortString, int defaultPort) {
|
||||
|
||||
Assert.notNull(hostPortString, "HostPortString must not be null");
|
||||
String host;
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2018-2023 the original author or authors.
|
||||
* Copyright 2018-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
+5
-8
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2018-2023 the original author or authors.
|
||||
* Copyright 2018-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -13,7 +13,7 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.client.erhlc;
|
||||
package org.springframework.data.elasticsearch.client;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
@@ -31,17 +31,14 @@ import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* RestHighLevelClientFactoryBean
|
||||
* RestClientFactoryBean
|
||||
*
|
||||
* @author Don Wellington
|
||||
* @author Peter-Josef Meisch
|
||||
* @deprecated since 5.0
|
||||
*/
|
||||
@Deprecated
|
||||
public class RestHighLevelClientFactoryBean
|
||||
implements FactoryBean<RestHighLevelClient>, InitializingBean, DisposableBean {
|
||||
public class RestClientFactoryBean implements FactoryBean<RestHighLevelClient>, InitializingBean, DisposableBean {
|
||||
|
||||
private static final Log LOGGER = LogFactory.getLog(RestHighLevelClientFactoryBean.class);
|
||||
private static final Log LOGGER = LogFactory.getLog(RestClientFactoryBean.class);
|
||||
|
||||
private @Nullable RestHighLevelClient client;
|
||||
private String hosts = "http://localhost:9200";
|
||||
+11
-18
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2018-2023 the original author or authors.
|
||||
* Copyright 2018-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -13,7 +13,7 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.client.erhlc;
|
||||
package org.springframework.data.elasticsearch.client;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.Closeable;
|
||||
@@ -43,10 +43,8 @@ import org.apache.http.protocol.HttpContext;
|
||||
import org.elasticsearch.client.RestClient;
|
||||
import org.elasticsearch.client.RestClientBuilder;
|
||||
import org.elasticsearch.client.RestHighLevelClient;
|
||||
import org.elasticsearch.client.RestHighLevelClientBuilder;
|
||||
import org.springframework.data.elasticsearch.client.ClientConfiguration;
|
||||
import org.springframework.data.elasticsearch.client.ClientLogger;
|
||||
import org.springframework.data.elasticsearch.support.HttpHeaders;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
@@ -60,9 +58,7 @@ import org.springframework.util.Assert;
|
||||
* @author Peter-Josef Meisch
|
||||
* @author Nic Hines
|
||||
* @since 3.2
|
||||
* @deprecated since 5.0
|
||||
*/
|
||||
@Deprecated
|
||||
public final class RestClients {
|
||||
|
||||
/**
|
||||
@@ -127,7 +123,8 @@ public final class RestClients {
|
||||
|
||||
for (ClientConfiguration.ClientConfigurationCallback<?> clientConfigurer : clientConfiguration
|
||||
.getClientConfigurers()) {
|
||||
if (clientConfigurer instanceof RestClientConfigurationCallback restClientConfigurationCallback) {
|
||||
if (clientConfigurer instanceof RestClientConfigurationCallback) {
|
||||
RestClientConfigurationCallback restClientConfigurationCallback = (RestClientConfigurationCallback) clientConfigurer;
|
||||
clientBuilder = restClientConfigurationCallback.configure(clientBuilder);
|
||||
}
|
||||
}
|
||||
@@ -135,7 +132,7 @@ public final class RestClients {
|
||||
return clientBuilder;
|
||||
});
|
||||
|
||||
RestHighLevelClient client = new RestHighLevelClientBuilder(builder.build()).setApiCompatibilityMode(true).build();
|
||||
RestHighLevelClient client = new RestHighLevelClient(builder);
|
||||
return () -> client;
|
||||
}
|
||||
|
||||
@@ -184,9 +181,7 @@ public final class RestClients {
|
||||
*
|
||||
* @see ClientLogger
|
||||
* @since 3.2
|
||||
* @deprecated since 5.0
|
||||
*/
|
||||
@Deprecated
|
||||
private static class HttpLoggingInterceptor implements HttpResponseInterceptor, HttpRequestInterceptor {
|
||||
|
||||
@Override
|
||||
@@ -199,9 +194,9 @@ public final class RestClients {
|
||||
context.setAttribute(RestClients.LOG_ID_ATTRIBUTE, logId);
|
||||
}
|
||||
|
||||
if (request instanceof HttpEntityEnclosingRequest entityRequest
|
||||
&& ((HttpEntityEnclosingRequest) request).getEntity() != null) {
|
||||
if (request instanceof HttpEntityEnclosingRequest && ((HttpEntityEnclosingRequest) request).getEntity() != null) {
|
||||
|
||||
HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
|
||||
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
|
||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
entity.writeTo(buffer);
|
||||
@@ -220,7 +215,7 @@ public final class RestClients {
|
||||
@Override
|
||||
public void process(HttpResponse response, HttpContext context) {
|
||||
String logId = (String) context.getAttribute(RestClients.LOG_ID_ATTRIBUTE);
|
||||
ClientLogger.logRawResponse(logId, response.getStatusLine().getStatusCode());
|
||||
ClientLogger.logRawResponse(logId, HttpStatus.resolve(response.getStatusLine().getStatusCode()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,7 +236,7 @@ public final class RestClients {
|
||||
public void process(HttpRequest request, HttpContext context) {
|
||||
HttpHeaders httpHeaders = headersSupplier.get();
|
||||
|
||||
if (httpHeaders != null && !httpHeaders.isEmpty()) {
|
||||
if (httpHeaders != null && httpHeaders != HttpHeaders.EMPTY) {
|
||||
Arrays.stream(toHeaderArray(httpHeaders)).forEach(request::addHeader);
|
||||
}
|
||||
}
|
||||
@@ -252,9 +247,7 @@ public final class RestClients {
|
||||
* the RestClient with a {@link HttpAsyncClientBuilder}
|
||||
*
|
||||
* @since 4.3
|
||||
* @deprecated since 5.0
|
||||
*/
|
||||
@Deprecated
|
||||
public interface RestClientConfigurationCallback
|
||||
extends ClientConfiguration.ClientConfigurationCallback<HttpAsyncClientBuilder> {
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2022-2023 the original author or authors.
|
||||
* Copyright 2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
/*
|
||||
* Copyright 2022-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.client;
|
||||
|
||||
/**
|
||||
* @author Peter-Josef Meisch
|
||||
*/
|
||||
public class UnsupportedClientOperationException extends RuntimeException {
|
||||
public UnsupportedClientOperationException(Class<?> clientClass, String operation) {
|
||||
super("Client %1$s does not support the operation %2$s".formatted(clientClass, operation));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2022-2023 the original author or authors.
|
||||
* Copyright 2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -19,7 +19,7 @@ import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
|
||||
|
||||
/**
|
||||
* Class to combine an Elasticsearch {@link co.elastic.clients.elasticsearch._types.aggregations.Aggregate} with its
|
||||
* name. Necessary as the Elasticsearch Aggregate does not know its name.
|
||||
* name. Necessary as the Elasticsearch Aggregate does not know i"s name.
|
||||
*
|
||||
* @author Peter-Josef Meisch
|
||||
* @since 4.4
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -18,7 +18,6 @@ package org.springframework.data.elasticsearch.client.elc;
|
||||
import co.elastic.clients.ApiClient;
|
||||
import co.elastic.clients.elasticsearch.cluster.ElasticsearchClusterClient;
|
||||
import co.elastic.clients.json.JsonpMapper;
|
||||
import co.elastic.clients.transport.Transport;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@@ -33,7 +32,7 @@ import org.springframework.util.Assert;
|
||||
* @author Peter-Josef Meisch
|
||||
* @since 4.4
|
||||
*/
|
||||
public abstract class ChildTemplate<T extends Transport, CLIENT extends ApiClient<T, CLIENT>> {
|
||||
public abstract class ChildTemplate<CLIENT extends ApiClient> {
|
||||
|
||||
protected final CLIENT client;
|
||||
protected final RequestConverter requestConverter;
|
||||
|
||||
+2
-4
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -18,7 +18,6 @@ package org.springframework.data.elasticsearch.client.elc;
|
||||
import co.elastic.clients.elasticsearch.cluster.ElasticsearchClusterClient;
|
||||
import co.elastic.clients.elasticsearch.cluster.HealthRequest;
|
||||
import co.elastic.clients.elasticsearch.cluster.HealthResponse;
|
||||
import co.elastic.clients.transport.ElasticsearchTransport;
|
||||
|
||||
import org.springframework.data.elasticsearch.core.cluster.ClusterHealth;
|
||||
import org.springframework.data.elasticsearch.core.cluster.ClusterOperations;
|
||||
@@ -30,8 +29,7 @@ import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverte
|
||||
* @author Peter-Josef Meisch
|
||||
* @since 4.4
|
||||
*/
|
||||
public class ClusterTemplate extends ChildTemplate<ElasticsearchTransport, ElasticsearchClusterClient>
|
||||
implements ClusterOperations {
|
||||
public class ClusterTemplate extends ChildTemplate<ElasticsearchClusterClient> implements ClusterOperations {
|
||||
|
||||
public ClusterTemplate(ElasticsearchClusterClient client, ElasticsearchConverter elasticsearchConverter) {
|
||||
super(client, elasticsearchConverter);
|
||||
|
||||
+26
-20
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -130,37 +130,37 @@ class CriteriaFilterProcessor {
|
||||
ObjectBuilder<? extends QueryVariant> queryBuilder = null;
|
||||
|
||||
switch (key) {
|
||||
case WITHIN -> {
|
||||
case WITHIN:
|
||||
Assert.isTrue(value instanceof Object[], "Value of a geo distance filter should be an array of two values.");
|
||||
queryBuilder = withinQuery(fieldName, (Object[]) value);
|
||||
}
|
||||
case BBOX -> {
|
||||
break;
|
||||
case BBOX:
|
||||
Assert.isTrue(value instanceof Object[],
|
||||
"Value of a boundedBy filter should be an array of one or two values.");
|
||||
queryBuilder = boundingBoxQuery(fieldName, (Object[]) value);
|
||||
}
|
||||
case GEO_INTERSECTS -> {
|
||||
break;
|
||||
case GEO_INTERSECTS:
|
||||
Assert.isTrue(value instanceof GeoJson<?>, "value of a GEO_INTERSECTS filter must be a GeoJson object");
|
||||
queryBuilder = geoJsonQuery(fieldName, (GeoJson<?>) value, "intersects");
|
||||
}
|
||||
case GEO_IS_DISJOINT -> {
|
||||
break;
|
||||
case GEO_IS_DISJOINT:
|
||||
Assert.isTrue(value instanceof GeoJson<?>, "value of a GEO_IS_DISJOINT filter must be a GeoJson object");
|
||||
queryBuilder = geoJsonQuery(fieldName, (GeoJson<?>) value, "disjoint");
|
||||
}
|
||||
case GEO_WITHIN -> {
|
||||
break;
|
||||
case GEO_WITHIN:
|
||||
Assert.isTrue(value instanceof GeoJson<?>, "value of a GEO_WITHIN filter must be a GeoJson object");
|
||||
queryBuilder = geoJsonQuery(fieldName, (GeoJson<?>) value, "within");
|
||||
}
|
||||
case GEO_CONTAINS -> {
|
||||
break;
|
||||
case GEO_CONTAINS:
|
||||
Assert.isTrue(value instanceof GeoJson<?>, "value of a GEO_CONTAINS filter must be a GeoJson object");
|
||||
queryBuilder = geoJsonQuery(fieldName, (GeoJson<?>) value, "contains");
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return Optional.ofNullable(queryBuilder != null ? queryBuilder.build()._toQuery() : null);
|
||||
}
|
||||
|
||||
private static ObjectBuilder<GeoDistanceQuery> withinQuery(String fieldName, Object... values) {
|
||||
private static ObjectBuilder<GeoDistanceQuery> withinQuery(String fieldName, Object[] values) {
|
||||
|
||||
Assert.noNullElements(values, "Geo distance filter takes 2 not null elements array as parameter.");
|
||||
Assert.isTrue(values.length == 2, "Geo distance filter takes a 2-elements array as parameter.");
|
||||
@@ -176,7 +176,8 @@ class CriteriaFilterProcessor {
|
||||
.distance(dist) //
|
||||
.distanceType(GeoDistanceType.Plane) //
|
||||
.location(location -> {
|
||||
if (values[0]instanceof GeoPoint loc) {
|
||||
if (values[0] instanceof GeoPoint) {
|
||||
GeoPoint loc = (GeoPoint) values[0];
|
||||
location.latlon(latlon -> latlon.lat(loc.getLat()).lon(loc.getLon()));
|
||||
} else if (values[0] instanceof Point) {
|
||||
GeoPoint loc = GeoPoint.fromPoint((Point) values[0]);
|
||||
@@ -194,7 +195,7 @@ class CriteriaFilterProcessor {
|
||||
});
|
||||
}
|
||||
|
||||
private static ObjectBuilder<GeoBoundingBoxQuery> boundingBoxQuery(String fieldName, Object... values) {
|
||||
private static ObjectBuilder<GeoBoundingBoxQuery> boundingBoxQuery(String fieldName, Object[] values) {
|
||||
|
||||
Assert.noNullElements(values, "Geo boundedBy filter takes a not null element array as parameter.");
|
||||
|
||||
@@ -239,12 +240,13 @@ class CriteriaFilterProcessor {
|
||||
)))));
|
||||
}
|
||||
|
||||
private static void twoParameterBBox(GeoBoundingBoxQuery.Builder queryBuilder, Object... values) {
|
||||
private static void twoParameterBBox(GeoBoundingBoxQuery.Builder queryBuilder, Object[] values) {
|
||||
|
||||
Assert.isTrue(allElementsAreOfType(values, GeoPoint.class) || allElementsAreOfType(values, String.class),
|
||||
" both elements of boundedBy filter must be type of GeoPoint or text(format lat,lon or geohash)");
|
||||
|
||||
if (values[0]instanceof GeoPoint topLeft) {
|
||||
if (values[0] instanceof GeoPoint) {
|
||||
GeoPoint topLeft = (GeoPoint) values[0];
|
||||
GeoPoint bottomRight = (GeoPoint) values[1];
|
||||
queryBuilder.boundingBox(bb -> bb //
|
||||
.tlbr(tlbr -> tlbr //
|
||||
@@ -327,8 +329,12 @@ class CriteriaFilterProcessor {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append((int) distance.getValue());
|
||||
switch ((Metrics) distance.getMetric()) {
|
||||
case KILOMETERS -> sb.append("km");
|
||||
case MILES -> sb.append("mi");
|
||||
case KILOMETERS:
|
||||
sb.append("km");
|
||||
break;
|
||||
case MILES:
|
||||
sb.append("mi");
|
||||
break;
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
+9
-35
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -15,7 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.client.elc;
|
||||
|
||||
import static org.springframework.data.elasticsearch.client.elc.Queries.*;
|
||||
import static org.springframework.data.elasticsearch.client.elc.QueryBuilders.*;
|
||||
import static org.springframework.util.StringUtils.*;
|
||||
|
||||
import co.elastic.clients.elasticsearch._types.FieldValue;
|
||||
@@ -28,6 +28,7 @@ import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.lucene.queryparser.flexible.standard.QueryParserUtil;
|
||||
import org.springframework.data.elasticsearch.annotations.FieldType;
|
||||
import org.springframework.data.elasticsearch.core.query.Criteria;
|
||||
import org.springframework.data.elasticsearch.core.query.Field;
|
||||
@@ -39,7 +40,6 @@ import org.springframework.util.Assert;
|
||||
* query.
|
||||
*
|
||||
* @author Peter-Josef Meisch
|
||||
* @author Ezequiel Antúnez Camacho
|
||||
* @since 4.4
|
||||
*/
|
||||
class CriteriaQueryProcessor {
|
||||
@@ -184,7 +184,7 @@ class CriteriaQueryProcessor {
|
||||
|
||||
Criteria.OperationKey key = entry.getKey();
|
||||
Object value = key.hasValue() ? entry.getValue() : null;
|
||||
String searchText = value != null ? escape(value.toString()) : "UNKNOWN_VALUE";
|
||||
String searchText = value != null ? QueryParserUtil.escape(value.toString()) : "UNKNOWN_VALUE";
|
||||
|
||||
Query.Builder queryBuilder = new Query.Builder();
|
||||
switch (key) {
|
||||
@@ -289,7 +289,8 @@ class CriteriaQueryProcessor {
|
||||
|
||||
break;
|
||||
case IN:
|
||||
if (value instanceof Iterable<?> iterable) {
|
||||
if (value instanceof Iterable) {
|
||||
Iterable<?> iterable = (Iterable<?>) value;
|
||||
if (isKeywordField) {
|
||||
queryBuilder.bool(bb -> bb //
|
||||
.must(mb -> mb //
|
||||
@@ -310,7 +311,8 @@ class CriteriaQueryProcessor {
|
||||
}
|
||||
break;
|
||||
case NOT_IN:
|
||||
if (value instanceof Iterable<?> iterable) {
|
||||
if (value instanceof Iterable) {
|
||||
Iterable<?> iterable = (Iterable<?>) value;
|
||||
if (isKeywordField) {
|
||||
queryBuilder.bool(bb -> bb //
|
||||
.mustNot(mnb -> mnb //
|
||||
@@ -330,13 +332,6 @@ class CriteriaQueryProcessor {
|
||||
throw new CriteriaQueryException("value for " + fieldName + " is not an Iterable");
|
||||
}
|
||||
break;
|
||||
case REGEXP:
|
||||
queryBuilder //
|
||||
.regexp(rb -> rb //
|
||||
.field(fieldName) //
|
||||
.value(value.toString()) //
|
||||
.boost(boost)); //
|
||||
break;
|
||||
default:
|
||||
throw new CriteriaQueryException("Could not build query for " + entry);
|
||||
}
|
||||
@@ -363,32 +358,11 @@ class CriteriaQueryProcessor {
|
||||
sb.append(' ');
|
||||
}
|
||||
sb.append('"');
|
||||
sb.append(escape(item.toString()));
|
||||
sb.append(QueryParserUtil.escape(item.toString()));
|
||||
sb.append('"');
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a String where those characters that TextParser expects to be escaped are escaped by a preceding
|
||||
* <code>\</code>. Copied from Apachae 2 licensed org.apache.lucene.queryparser.flexible.standard.QueryParserUtil
|
||||
* class
|
||||
*/
|
||||
public static String escape(String s) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
// These characters are part of the query syntax and must be escaped
|
||||
if (c == '\\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')' || c == ':' || c == '^' || c == '['
|
||||
|| c == ']' || c == '\"' || c == '{' || c == '}' || c == '~' || c == '*' || c == '?' || c == '|' || c == '&'
|
||||
|| c == '/') {
|
||||
sb.append('\\');
|
||||
}
|
||||
sb.append(c);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+10
-25
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -19,7 +19,6 @@ import co.elastic.clients.elasticsearch.core.GetResponse;
|
||||
import co.elastic.clients.elasticsearch.core.MgetResponse;
|
||||
import co.elastic.clients.elasticsearch.core.explain.ExplanationDetail;
|
||||
import co.elastic.clients.elasticsearch.core.get.GetResult;
|
||||
import co.elastic.clients.elasticsearch.core.search.CompletionSuggestOption;
|
||||
import co.elastic.clients.elasticsearch.core.search.Hit;
|
||||
import co.elastic.clients.elasticsearch.core.search.NestedIdentity;
|
||||
import co.elastic.clients.json.JsonData;
|
||||
@@ -73,7 +72,7 @@ final class DocumentAdapters {
|
||||
Map<String, SearchDocumentResponse> innerHits = new LinkedHashMap<>();
|
||||
hit.innerHits().forEach((name, innerHitsResult) -> {
|
||||
// noinspection ReturnOfNull
|
||||
innerHits.put(name, SearchDocumentResponseBuilder.from(innerHitsResult.hits(), null, null, null, null,
|
||||
innerHits.put(name, SearchDocumentResponseBuilder.from(innerHitsResult.hits(), null, null, null,
|
||||
searchDocument -> null, jsonpMapper));
|
||||
});
|
||||
|
||||
@@ -101,12 +100,12 @@ final class DocumentAdapters {
|
||||
EntityAsMap hitFieldsAsMap = fromFields.apply(hit.fields());
|
||||
|
||||
Map<String, List<Object>> documentFields = new LinkedHashMap<>();
|
||||
hitFieldsAsMap.forEach((key, value) -> {
|
||||
if (value instanceof List) {
|
||||
hitFieldsAsMap.entrySet().forEach(entry -> {
|
||||
if (entry.getValue() instanceof List) {
|
||||
// noinspection unchecked
|
||||
documentFields.put(key, (List<Object>) value);
|
||||
documentFields.put(entry.getKey(), (List<Object>) entry.getValue());
|
||||
} else {
|
||||
documentFields.put(key, Collections.singletonList(value));
|
||||
documentFields.put(entry.getKey(), Collections.singletonList(entry.getValue()));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -117,7 +116,8 @@ final class DocumentAdapters {
|
||||
} else {
|
||||
if (source instanceof EntityAsMap) {
|
||||
document = Document.from((EntityAsMap) source);
|
||||
} else if (source instanceof JsonData jsonData) {
|
||||
} else if (source instanceof JsonData) {
|
||||
JsonData jsonData = (JsonData) source;
|
||||
document = Document.from(jsonData.to(EntityAsMap.class));
|
||||
} else {
|
||||
|
||||
@@ -138,23 +138,8 @@ final class DocumentAdapters {
|
||||
document.setPrimaryTerm(hit.primaryTerm() != null && hit.primaryTerm() > 0 ? hit.primaryTerm() : 0);
|
||||
|
||||
float score = hit.score() != null ? hit.score().floatValue() : Float.NaN;
|
||||
return new SearchDocumentAdapter(document, score, hit.sort().stream().map(TypeUtils::toString).toArray(),
|
||||
documentFields, highlightFields, innerHits, nestedMetaData, explanation, matchedQueries, hit.routing());
|
||||
}
|
||||
|
||||
public static SearchDocument from(CompletionSuggestOption<EntityAsMap> completionSuggestOption) {
|
||||
|
||||
Document document = completionSuggestOption.source() != null ? Document.from(completionSuggestOption.source())
|
||||
: Document.create();
|
||||
document.setIndex(completionSuggestOption.index());
|
||||
|
||||
if (completionSuggestOption.id() != null) {
|
||||
document.setId(completionSuggestOption.id());
|
||||
}
|
||||
|
||||
float score = completionSuggestOption.score() != null ? completionSuggestOption.score().floatValue() : Float.NaN;
|
||||
return new SearchDocumentAdapter(document, score, new Object[] {}, Collections.emptyMap(), Collections.emptyMap(),
|
||||
Collections.emptyMap(), null, null, null, completionSuggestOption.routing());
|
||||
return new SearchDocumentAdapter(document, score, hit.sort().toArray(new String[0]), documentFields,
|
||||
highlightFields, innerHits, nestedMetaData, explanation, matchedQueries, hit.routing());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2022-2023 the original author or authors.
|
||||
* Copyright 2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
+16
-32
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -18,61 +18,45 @@ package org.springframework.data.elasticsearch.client.elc;
|
||||
import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.data.elasticsearch.core.AggregationsContainer;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* AggregationsContainer implementation for the Elasticsearch aggregations.
|
||||
*
|
||||
* @author Peter-Josef Meisch
|
||||
* @author Sascha Woo
|
||||
* @since 4.4
|
||||
*/
|
||||
public class ElasticsearchAggregations implements AggregationsContainer<List<ElasticsearchAggregation>> {
|
||||
|
||||
private final List<ElasticsearchAggregation> aggregations;
|
||||
private final Map<String, ElasticsearchAggregation> aggregationsAsMap;
|
||||
|
||||
public ElasticsearchAggregations(Map<String, Aggregate> aggregations) {
|
||||
public ElasticsearchAggregations(List<ElasticsearchAggregation> aggregations) {
|
||||
|
||||
Assert.notNull(aggregations, "aggregations must not be null");
|
||||
|
||||
aggregationsAsMap = new HashMap<>();
|
||||
aggregations.forEach((name, aggregate) -> aggregationsAsMap //
|
||||
.put(name, new ElasticsearchAggregation(new Aggregation(name, aggregate))));
|
||||
this.aggregations = aggregations;
|
||||
}
|
||||
|
||||
this.aggregations = new ArrayList<>(aggregationsAsMap.values());
|
||||
/**
|
||||
* convenience constructor taking a map as it is returned from the new Elasticsearch client.
|
||||
*
|
||||
* @param aggregationsMap aggregate map
|
||||
*/
|
||||
public ElasticsearchAggregations(Map<String, Aggregate> aggregationsMap) {
|
||||
|
||||
Assert.notNull(aggregationsMap, "aggregationsMap must not be null");
|
||||
|
||||
aggregations = new ArrayList<>(aggregationsMap.size());
|
||||
aggregationsMap
|
||||
.forEach((name, aggregate) -> aggregations.add(new ElasticsearchAggregation(new Aggregation(name, aggregate))));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ElasticsearchAggregation> aggregations() {
|
||||
return aggregations;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the {@link ElasticsearchAggregation}s keyed by aggregation name.
|
||||
*/
|
||||
public Map<String, ElasticsearchAggregation> aggregationsAsMap() {
|
||||
return aggregationsAsMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the aggregation that is associated with the specified name.
|
||||
*
|
||||
* @param name the name of the aggregation
|
||||
* @return the aggregation or {@literal null} if not found
|
||||
*/
|
||||
@Nullable
|
||||
public ElasticsearchAggregation get(String name) {
|
||||
|
||||
Assert.notNull(name, "name must not be null");
|
||||
|
||||
return aggregationsAsMap.get(name);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
/*
|
||||
* Copyright 2022-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.client.elc;
|
||||
|
||||
import org.springframework.beans.factory.support.AbstractBeanDefinition;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||
import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser;
|
||||
import org.springframework.beans.factory.xml.ParserContext;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* @author Peter-Josef Meisch
|
||||
* @since 5.0
|
||||
*/
|
||||
public class ElasticsearchClientBeanDefinitionParser extends AbstractBeanDefinitionParser {
|
||||
|
||||
@Override
|
||||
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ElasticsearchClientFactoryBean.class);
|
||||
setConfigurations(element, builder);
|
||||
return getSourcedBeanDefinition(builder, element, parserContext);
|
||||
}
|
||||
|
||||
private void setConfigurations(Element element, BeanDefinitionBuilder builder) {
|
||||
builder.addPropertyValue("hosts", element.getAttribute("hosts"));
|
||||
}
|
||||
|
||||
private AbstractBeanDefinition getSourcedBeanDefinition(BeanDefinitionBuilder builder, Element source,
|
||||
ParserContext context) {
|
||||
AbstractBeanDefinition definition = builder.getBeanDefinition();
|
||||
definition.setSource(context.extractSource(source));
|
||||
return definition;
|
||||
}
|
||||
}
|
||||
-97
@@ -1,97 +0,0 @@
|
||||
/*
|
||||
* Copyright 2022-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.client.elc;
|
||||
|
||||
import co.elastic.clients.elasticsearch.ElasticsearchClient;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.beans.factory.DisposableBean;
|
||||
import org.springframework.beans.factory.FactoryBean;
|
||||
import org.springframework.beans.factory.FactoryBeanNotInitializedException;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.data.elasticsearch.client.ClientConfiguration;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* ElasticsearchClientFactoryBean
|
||||
*
|
||||
* @author Peter-Josef Meisch
|
||||
* @since 5.0
|
||||
*/
|
||||
public class ElasticsearchClientFactoryBean
|
||||
implements FactoryBean<ElasticsearchClient>, InitializingBean, DisposableBean {
|
||||
|
||||
private static final Log LOGGER = LogFactory.getLog(ElasticsearchClientFactoryBean.class);
|
||||
|
||||
private @Nullable AutoCloseableElasticsearchClient client;
|
||||
private String hosts = "http://localhost:9200";
|
||||
static final String COMMA = ",";
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
try {
|
||||
LOGGER.info("Closing elasticSearch client");
|
||||
if (client != null) {
|
||||
client.close();
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
LOGGER.error("Error closing ElasticSearch client: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
buildClient();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ElasticsearchClient getObject() {
|
||||
|
||||
if (client == null) {
|
||||
throw new FactoryBeanNotInitializedException();
|
||||
}
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getObjectType() {
|
||||
return ElasticsearchClient.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSingleton() {
|
||||
return false;
|
||||
}
|
||||
|
||||
protected void buildClient() throws Exception {
|
||||
|
||||
Assert.hasText(hosts, "[Assertion Failed] At least one host must be set.");
|
||||
|
||||
var clientConfiguration = ClientConfiguration.builder().connectedTo(hosts).build();
|
||||
client = (AutoCloseableElasticsearchClient) ElasticsearchClients.createImperative(clientConfiguration);
|
||||
}
|
||||
|
||||
public void setHosts(String hosts) {
|
||||
this.hosts = hosts;
|
||||
}
|
||||
|
||||
public String getHosts() {
|
||||
return this.hosts;
|
||||
}
|
||||
}
|
||||
+35
-59
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -19,8 +19,6 @@ import co.elastic.clients.elasticsearch.ElasticsearchClient;
|
||||
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
|
||||
import co.elastic.clients.transport.ElasticsearchTransport;
|
||||
import co.elastic.clients.transport.TransportOptions;
|
||||
import co.elastic.clients.transport.TransportUtils;
|
||||
import co.elastic.clients.transport.Version;
|
||||
import co.elastic.clients.transport.rest_client.RestClientOptions;
|
||||
import co.elastic.clients.transport.rest_client.RestClientTransport;
|
||||
|
||||
@@ -30,27 +28,32 @@ import java.net.InetSocketAddress;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.http.*;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpEntityEnclosingRequest;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.HttpRequestInterceptor;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.HttpResponseInterceptor;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.entity.ByteArrayEntity;
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
|
||||
import org.apache.http.message.BasicHeader;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.elasticsearch.client.RequestOptions;
|
||||
import org.elasticsearch.client.RestClient;
|
||||
import org.elasticsearch.client.RestClientBuilder;
|
||||
import org.springframework.data.elasticsearch.client.ClientConfiguration;
|
||||
import org.springframework.data.elasticsearch.client.ClientLogger;
|
||||
import org.springframework.data.elasticsearch.support.HttpHeaders;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
|
||||
/**
|
||||
* Utility class to create the different Elasticsearch clients
|
||||
@@ -192,10 +195,6 @@ public final class ElasticsearchClients {
|
||||
}
|
||||
|
||||
builder.setHttpClientConfigCallback(clientBuilder -> {
|
||||
if (clientConfiguration.getCaFingerprint().isPresent()) {
|
||||
clientBuilder
|
||||
.setSSLContext(TransportUtils.sslContextFromCaFingerprint(clientConfiguration.getCaFingerprint().get()));
|
||||
}
|
||||
clientConfiguration.getSslContext().ifPresent(clientBuilder::setSSLContext);
|
||||
clientConfiguration.getHostNameVerifier().ifPresent(clientBuilder::setSSLHostnameVerifier);
|
||||
clientBuilder.addInterceptorLast(new CustomHeaderInjector(clientConfiguration.getHeadersSupplier()));
|
||||
@@ -227,20 +226,14 @@ public final class ElasticsearchClients {
|
||||
|
||||
for (ClientConfiguration.ClientConfigurationCallback<?> clientConfigurer : clientConfiguration
|
||||
.getClientConfigurers()) {
|
||||
if (clientConfigurer instanceof ElasticsearchHttpClientConfigurationCallback restClientConfigurationCallback) {
|
||||
if (clientConfigurer instanceof ElasticsearchClientConfigurationCallback) {
|
||||
ElasticsearchClientConfigurationCallback restClientConfigurationCallback = (ElasticsearchClientConfigurationCallback) clientConfigurer;
|
||||
clientBuilder = restClientConfigurationCallback.configure(clientBuilder);
|
||||
}
|
||||
}
|
||||
|
||||
return clientBuilder;
|
||||
});
|
||||
|
||||
for (ClientConfiguration.ClientConfigurationCallback<?> clientConfigurationCallback : clientConfiguration
|
||||
.getClientConfigurers()) {
|
||||
if (clientConfigurationCallback instanceof ElasticsearchRestClientConfigurationCallback configurationCallback) {
|
||||
builder = configurationCallback.configure(builder);
|
||||
}
|
||||
}
|
||||
return builder;
|
||||
}
|
||||
|
||||
@@ -249,27 +242,12 @@ public final class ElasticsearchClients {
|
||||
|
||||
TransportOptions.Builder transportOptionsBuilder = transportOptions != null ? transportOptions.toBuilder()
|
||||
: new RestClientOptions(RequestOptions.DEFAULT).toBuilder();
|
||||
|
||||
ContentType jsonContentType = Version.VERSION == null ? ContentType.APPLICATION_JSON
|
||||
: ContentType.create("application/vnd.elasticsearch+json",
|
||||
new BasicNameValuePair("compatible-with", String.valueOf(Version.VERSION.major())));
|
||||
|
||||
Consumer<String> setHeaderIfNotPresent = header -> {
|
||||
if (transportOptionsBuilder.build().headers().stream() //
|
||||
.noneMatch((h) -> h.getKey().equalsIgnoreCase(header))) {
|
||||
// need to add the compatibility header, this is only done automatically when not passing in custom options.
|
||||
// code copied from RestClientTransport as it is not available outside the package
|
||||
transportOptionsBuilder.addHeader(header, jsonContentType.toString());
|
||||
}
|
||||
};
|
||||
|
||||
setHeaderIfNotPresent.accept("Content-Type");
|
||||
setHeaderIfNotPresent.accept("Accept");
|
||||
|
||||
TransportOptions transportOptionsWithHeader = transportOptionsBuilder
|
||||
.addHeader(X_SPRING_DATA_ELASTICSEARCH_CLIENT, clientType).build();
|
||||
|
||||
return new RestClientTransport(restClient, new JacksonJsonpMapper(), transportOptionsWithHeader);
|
||||
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper(),
|
||||
transportOptionsWithHeader);
|
||||
return transport;
|
||||
}
|
||||
|
||||
private static List<String> formattedHosts(List<InetSocketAddress> hosts, boolean useSsl) {
|
||||
@@ -289,9 +267,7 @@ public final class ElasticsearchClients {
|
||||
*
|
||||
* @see ClientLogger
|
||||
* @since 4.4
|
||||
* @deprecated since 5.0
|
||||
*/
|
||||
@Deprecated
|
||||
private static class HttpLoggingInterceptor implements HttpResponseInterceptor, HttpRequestInterceptor {
|
||||
|
||||
@Override
|
||||
@@ -309,9 +285,9 @@ public final class ElasticsearchClients {
|
||||
+ ((header.getName().equals("Authorization")) ? ": *****" : ": " + header.getValue()))
|
||||
.collect(Collectors.joining(", ", "[", "]"));
|
||||
|
||||
if (request instanceof HttpEntityEnclosingRequest entityRequest
|
||||
&& ((HttpEntityEnclosingRequest) request).getEntity() != null) {
|
||||
if (request instanceof HttpEntityEnclosingRequest && ((HttpEntityEnclosingRequest) request).getEntity() != null) {
|
||||
|
||||
HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
|
||||
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
|
||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
entity.writeTo(buffer);
|
||||
@@ -338,9 +314,9 @@ public final class ElasticsearchClients {
|
||||
+ ((header.getName().equals("Authorization")) ? ": *****" : ": " + header.getValue()))
|
||||
.collect(Collectors.joining(", ", "[", "]"));
|
||||
|
||||
// no way of logging the body, in this callback, it is not read yet, later there is no callback possibility in
|
||||
// no way of logging the body, in this callback, it is not read yset, later there is no callback possibility in
|
||||
// RestClient or RestClientTransport
|
||||
ClientLogger.logRawResponse(logId, response.getStatusLine().getStatusCode(), headers);
|
||||
ClientLogger.logRawResponse(logId, HttpStatus.resolve(response.getStatusLine().getStatusCode()), headers);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -361,7 +337,7 @@ public final class ElasticsearchClients {
|
||||
public void process(HttpRequest request, HttpContext context) {
|
||||
HttpHeaders httpHeaders = headersSupplier.get();
|
||||
|
||||
if (httpHeaders != null && !httpHeaders.isEmpty()) {
|
||||
if (httpHeaders != null && httpHeaders != HttpHeaders.EMPTY) {
|
||||
Arrays.stream(toHeaderArray(httpHeaders)).forEach(request::addHeader);
|
||||
}
|
||||
}
|
||||
@@ -369,37 +345,37 @@ public final class ElasticsearchClients {
|
||||
|
||||
/**
|
||||
* {@link org.springframework.data.elasticsearch.client.ClientConfiguration.ClientConfigurationCallback} to configure
|
||||
* the Elasticsearch RestClient's Http client with a {@link HttpAsyncClientBuilder}
|
||||
* the RestClient with a {@link HttpAsyncClientBuilder}
|
||||
*
|
||||
* @since 4.4
|
||||
*/
|
||||
public interface ElasticsearchHttpClientConfigurationCallback
|
||||
public interface ElasticsearchClientConfigurationCallback
|
||||
extends ClientConfiguration.ClientConfigurationCallback<HttpAsyncClientBuilder> {
|
||||
|
||||
static ElasticsearchHttpClientConfigurationCallback from(
|
||||
Function<HttpAsyncClientBuilder, HttpAsyncClientBuilder> httpClientBuilderCallback) {
|
||||
static ElasticsearchClientConfigurationCallback from(
|
||||
Function<HttpAsyncClientBuilder, HttpAsyncClientBuilder> clientBuilderCallback) {
|
||||
|
||||
Assert.notNull(httpClientBuilderCallback, "httpClientBuilderCallback must not be null");
|
||||
Assert.notNull(clientBuilderCallback, "clientBuilderCallback must not be null");
|
||||
|
||||
return httpClientBuilderCallback::apply;
|
||||
// noinspection NullableProblems
|
||||
return clientBuilderCallback::apply;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link org.springframework.data.elasticsearch.client.ClientConfiguration.ClientConfigurationCallback} to configure
|
||||
* the RestClient client with a {@link RestClientBuilder}
|
||||
* the ReactiveElasticsearchClient with a {@link WebClient}
|
||||
*
|
||||
* @since 5.0
|
||||
* @since 4.4
|
||||
*/
|
||||
public interface ElasticsearchRestClientConfigurationCallback
|
||||
extends ClientConfiguration.ClientConfigurationCallback<RestClientBuilder> {
|
||||
public interface WebClientConfigurationCallback extends ClientConfiguration.ClientConfigurationCallback<WebClient> {
|
||||
|
||||
static ElasticsearchRestClientConfigurationCallback from(
|
||||
Function<RestClientBuilder, RestClientBuilder> restClientBuilderCallback) {
|
||||
static WebClientConfigurationCallback from(Function<WebClient, WebClient> webClientCallback) {
|
||||
|
||||
Assert.notNull(restClientBuilderCallback, "restClientBuilderCallback must not be null");
|
||||
Assert.notNull(webClientCallback, "webClientCallback must not be null");
|
||||
|
||||
return restClientBuilderCallback::apply;
|
||||
// noinspection NullableProblems
|
||||
return webClientCallback::apply;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -42,7 +42,7 @@ public abstract class ElasticsearchConfiguration extends ElasticsearchConfigurat
|
||||
*
|
||||
* @return configuration, must not be {@literal null}
|
||||
*/
|
||||
@Bean(name="elasticsearchClientConfiguration")
|
||||
@Bean
|
||||
public abstract ClientConfiguration clientConfiguration();
|
||||
|
||||
/**
|
||||
@@ -52,7 +52,7 @@ public abstract class ElasticsearchConfiguration extends ElasticsearchConfigurat
|
||||
* @return RestClient
|
||||
*/
|
||||
@Bean
|
||||
public RestClient elasticsearchRestClient(ClientConfiguration clientConfiguration) {
|
||||
public RestClient restClient(ClientConfiguration clientConfiguration) {
|
||||
|
||||
Assert.notNull(clientConfiguration, "clientConfiguration must not be null");
|
||||
|
||||
|
||||
+17
-20
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -30,8 +30,8 @@ import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.dao.OptimisticLockingFailureException;
|
||||
import org.springframework.dao.support.PersistenceExceptionTranslator;
|
||||
import org.springframework.data.elasticsearch.NoSuchIndexException;
|
||||
import org.springframework.data.elasticsearch.ResourceNotFoundException;
|
||||
import org.springframework.data.elasticsearch.UncategorizedElasticsearchException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
/**
|
||||
* Simple {@link PersistenceExceptionTranslator} for Elasticsearch. Convert the given runtime exception to an
|
||||
@@ -72,31 +72,26 @@ public class ElasticsearchExceptionTranslator implements PersistenceExceptionTra
|
||||
return new OptimisticLockingFailureException("Cannot index a document due to seq_no+primary_term conflict", ex);
|
||||
}
|
||||
|
||||
if (ex instanceof ElasticsearchException elasticsearchException) {
|
||||
if (ex instanceof ElasticsearchException) {
|
||||
ElasticsearchException elasticsearchException = (ElasticsearchException) ex;
|
||||
|
||||
ErrorResponse response = elasticsearchException.response();
|
||||
var errorType = response.error().type();
|
||||
var errorReason = response.error().reason() != null ? response.error().reason() : "undefined reason";
|
||||
|
||||
if (response.status() == 404) {
|
||||
if (response.status() == HttpStatus.NOT_FOUND.value()
|
||||
&& "index_not_found_exception".equals(response.error().type())) {
|
||||
|
||||
if ("index_not_found_exception".equals(errorType)) {
|
||||
// noinspection RegExpRedundantEscape
|
||||
Pattern pattern = Pattern.compile(".*no such index \\[(.*)\\]");
|
||||
String index = "";
|
||||
Matcher matcher = pattern.matcher(errorReason);
|
||||
if (matcher.matches()) {
|
||||
index = matcher.group(1);
|
||||
}
|
||||
return new NoSuchIndexException(index);
|
||||
Pattern pattern = Pattern.compile(".*no such index \\[(.*)\\]");
|
||||
String index = "";
|
||||
Matcher matcher = pattern.matcher(response.error().reason());
|
||||
if (matcher.matches()) {
|
||||
index = matcher.group(1);
|
||||
}
|
||||
|
||||
return new ResourceNotFoundException(errorReason);
|
||||
return new NoSuchIndexException(index);
|
||||
}
|
||||
String body = JsonUtils.toJson(response, jsonpMapper);
|
||||
|
||||
if (errorType != null && errorType.contains("validation_exception")) {
|
||||
return new DataIntegrityViolationException(errorReason);
|
||||
if (response.error().type().contains("validation_exception")) {
|
||||
return new DataIntegrityViolationException(response.error().reason());
|
||||
}
|
||||
|
||||
return new UncategorizedElasticsearchException(ex.getMessage(), response.status(), body, ex);
|
||||
@@ -114,7 +109,9 @@ public class ElasticsearchExceptionTranslator implements PersistenceExceptionTra
|
||||
Integer status = null;
|
||||
String message = null;
|
||||
|
||||
if (exception instanceof ResponseException responseException) {
|
||||
|
||||
if (exception instanceof ResponseException) {
|
||||
ResponseException responseException = (ResponseException) exception;
|
||||
status = responseException.getResponse().getStatusLine().getStatusCode();
|
||||
message = responseException.getMessage();
|
||||
} else if (exception.getCause() != null) {
|
||||
|
||||
+30
-139
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -27,7 +27,6 @@ import co.elastic.clients.json.JsonpMapper;
|
||||
import co.elastic.clients.transport.Version;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
@@ -55,12 +54,10 @@ import org.springframework.data.elasticsearch.core.query.ByQueryResponse;
|
||||
import org.springframework.data.elasticsearch.core.query.IndexQuery;
|
||||
import org.springframework.data.elasticsearch.core.query.MoreLikeThisQuery;
|
||||
import org.springframework.data.elasticsearch.core.query.Query;
|
||||
import org.springframework.data.elasticsearch.core.query.SearchTemplateQuery;
|
||||
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
|
||||
import org.springframework.data.elasticsearch.core.query.UpdateResponse;
|
||||
import org.springframework.data.elasticsearch.core.reindex.ReindexRequest;
|
||||
import org.springframework.data.elasticsearch.core.reindex.ReindexResponse;
|
||||
import org.springframework.data.elasticsearch.core.script.Script;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
@@ -69,7 +66,6 @@ import org.springframework.util.Assert;
|
||||
* Elasticsearch client.
|
||||
*
|
||||
* @author Peter-Josef Meisch
|
||||
* @author Hamid Rahimi
|
||||
* @since 4.4
|
||||
*/
|
||||
public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
|
||||
@@ -83,17 +79,6 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
|
||||
private final ElasticsearchExceptionTranslator exceptionTranslator;
|
||||
|
||||
// region _initialization
|
||||
public ElasticsearchTemplate(ElasticsearchClient client) {
|
||||
|
||||
Assert.notNull(client, "client must not be null");
|
||||
|
||||
this.client = client;
|
||||
this.jsonpMapper = client._transport().jsonpMapper();
|
||||
requestConverter = new RequestConverter(elasticsearchConverter, jsonpMapper);
|
||||
responseConverter = new ResponseConverter(jsonpMapper);
|
||||
exceptionTranslator = new ElasticsearchExceptionTranslator(jsonpMapper);
|
||||
}
|
||||
|
||||
public ElasticsearchTemplate(ElasticsearchClient client, ElasticsearchConverter elasticsearchConverter) {
|
||||
super(elasticsearchConverter);
|
||||
|
||||
@@ -115,20 +100,16 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
|
||||
// region child templates
|
||||
@Override
|
||||
public IndexOperations indexOps(Class<?> clazz) {
|
||||
return new IndicesTemplate(client.indices(), getClusterTemplate(), elasticsearchConverter, clazz);
|
||||
return new IndicesTemplate(client.indices(), elasticsearchConverter, clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IndexOperations indexOps(IndexCoordinates index) {
|
||||
return new IndicesTemplate(client.indices(), getClusterTemplate(), elasticsearchConverter, index);
|
||||
return new IndicesTemplate(client.indices(), elasticsearchConverter, index);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClusterOperations cluster() {
|
||||
return getClusterTemplate();
|
||||
}
|
||||
|
||||
private ClusterTemplate getClusterTemplate() {
|
||||
return new ClusterTemplate(client.cluster(), elasticsearchConverter);
|
||||
}
|
||||
// endregion
|
||||
@@ -178,8 +159,8 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
|
||||
|
||||
Assert.notNull(query, "query must not be null");
|
||||
|
||||
DeleteByQueryRequest request = requestConverter.documentDeleteByQueryRequest(query, routingResolver.getRouting(),
|
||||
clazz, index, getRefreshPolicy());
|
||||
DeleteByQueryRequest request = requestConverter.documentDeleteByQueryRequest(query, clazz, index,
|
||||
getRefreshPolicy());
|
||||
|
||||
DeleteByQueryResponse response = execute(client -> client.deleteByQuery(request));
|
||||
|
||||
@@ -222,8 +203,8 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
|
||||
Object queryObject = query.getObject();
|
||||
|
||||
if (queryObject != null) {
|
||||
query.setObject(updateIndexedObject(queryObject, new IndexedObjectInformation(indexResponse.id(),
|
||||
indexResponse.index(), indexResponse.seqNo(), indexResponse.primaryTerm(), indexResponse.version())));
|
||||
query.setObject(updateIndexedObject(queryObject, IndexedObjectInformation.of(indexResponse.id(),
|
||||
indexResponse.seqNo(), indexResponse.primaryTerm(), indexResponse.version())));
|
||||
}
|
||||
|
||||
return indexResponse.id();
|
||||
@@ -292,18 +273,19 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
|
||||
// endregion
|
||||
|
||||
@Override
|
||||
public String getClusterVersion() {
|
||||
protected String getClusterVersion() {
|
||||
return execute(client -> client.info().version().number());
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVendor() {
|
||||
protected String getVendor() {
|
||||
return "Elasticsearch";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getRuntimeLibraryVersion() {
|
||||
return Version.VERSION != null ? Version.VERSION.toString() : "0.0.0.?";
|
||||
protected String getRuntimeLibraryVersion() {
|
||||
return Version.VERSION.toString();
|
||||
}
|
||||
|
||||
// region search operations
|
||||
@@ -313,8 +295,7 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
|
||||
Assert.notNull(query, "query must not be null");
|
||||
Assert.notNull(index, "index must not be null");
|
||||
|
||||
SearchRequest searchRequest = requestConverter.searchRequest(query, routingResolver.getRouting(), clazz, index,
|
||||
true);
|
||||
SearchRequest searchRequest = requestConverter.searchRequest(query, clazz, index, true, false);
|
||||
|
||||
SearchResponse<EntityAsMap> searchResponse = execute(client -> client.search(searchRequest, EntityAsMap.class));
|
||||
|
||||
@@ -325,22 +306,11 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
|
||||
public <T> SearchHits<T> search(Query query, Class<T> clazz, IndexCoordinates index) {
|
||||
|
||||
Assert.notNull(query, "query must not be null");
|
||||
Assert.notNull(clazz, "clazz must not be null");
|
||||
Assert.notNull(index, "index must not be null");
|
||||
|
||||
if (query instanceof SearchTemplateQuery searchTemplateQuery) {
|
||||
return doSearch(searchTemplateQuery, clazz, index);
|
||||
} else {
|
||||
return doSearch(query, clazz, index);
|
||||
}
|
||||
}
|
||||
|
||||
protected <T> SearchHits<T> doSearch(Query query, Class<T> clazz, IndexCoordinates index) {
|
||||
SearchRequest searchRequest = requestConverter.searchRequest(query, routingResolver.getRouting(), clazz, index,
|
||||
false);
|
||||
SearchRequest searchRequest = requestConverter.searchRequest(query, clazz, index, false, false);
|
||||
SearchResponse<EntityAsMap> searchResponse = execute(client -> client.search(searchRequest, EntityAsMap.class));
|
||||
|
||||
// noinspection DuplicatedCode
|
||||
ReadDocumentCallback<T> readDocumentCallback = new ReadDocumentCallback<>(elasticsearchConverter, clazz, index);
|
||||
SearchDocumentResponse.EntityCreator<T> entityCreator = getEntityCreator(readDocumentCallback);
|
||||
SearchDocumentResponseCallback<SearchHits<T>> callback = new ReadSearchDocumentResponseCallback<>(clazz, index);
|
||||
@@ -348,18 +318,6 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
|
||||
return callback.doWith(SearchDocumentResponseBuilder.from(searchResponse, entityCreator, jsonpMapper));
|
||||
}
|
||||
|
||||
protected <T> SearchHits<T> doSearch(SearchTemplateQuery query, Class<T> clazz, IndexCoordinates index) {
|
||||
var searchTemplateRequest = requestConverter.searchTemplate(query, routingResolver.getRouting(), index);
|
||||
var searchTemplateResponse = execute(client -> client.searchTemplate(searchTemplateRequest, EntityAsMap.class));
|
||||
|
||||
// noinspection DuplicatedCode
|
||||
ReadDocumentCallback<T> readDocumentCallback = new ReadDocumentCallback<>(elasticsearchConverter, clazz, index);
|
||||
SearchDocumentResponse.EntityCreator<T> entityCreator = getEntityCreator(readDocumentCallback);
|
||||
SearchDocumentResponseCallback<SearchHits<T>> callback = new ReadSearchDocumentResponseCallback<>(clazz, index);
|
||||
|
||||
return callback.doWith(SearchDocumentResponseBuilder.from(searchTemplateResponse, entityCreator, jsonpMapper));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected <T> SearchHits<T> doSearch(MoreLikeThisQuery query, Class<T> clazz, IndexCoordinates index) {
|
||||
|
||||
@@ -374,21 +332,20 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> SearchScrollHits<T> searchScrollStart(long scrollTimeInMillis, Query query, Class<T> clazz,
|
||||
protected <T> SearchScrollHits<T> searchScrollStart(long scrollTimeInMillis, Query query, Class<T> clazz,
|
||||
IndexCoordinates index) {
|
||||
|
||||
Assert.notNull(query, "query must not be null");
|
||||
Assert.notNull(query.getPageable(), "pageable of query must not be null.");
|
||||
|
||||
SearchRequest request = requestConverter.searchRequest(query, routingResolver.getRouting(), clazz, index, false,
|
||||
scrollTimeInMillis);
|
||||
SearchRequest request = requestConverter.searchRequest(query, clazz, index, false, scrollTimeInMillis);
|
||||
SearchResponse<EntityAsMap> response = execute(client -> client.search(request, EntityAsMap.class));
|
||||
|
||||
return getSearchScrollHits(clazz, index, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> SearchScrollHits<T> searchScrollContinue(String scrollId, long scrollTimeInMillis, Class<T> clazz,
|
||||
protected <T> SearchScrollHits<T> searchScrollContinue(String scrollId, long scrollTimeInMillis, Class<T> clazz,
|
||||
IndexCoordinates index) {
|
||||
|
||||
Assert.notNull(scrollId, "scrollId must not be null");
|
||||
@@ -411,7 +368,7 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void searchScrollClear(List<String> scrollIds) {
|
||||
protected void searchScrollClear(List<String> scrollIds) {
|
||||
|
||||
Assert.notNull(scrollIds, "scrollIds must not be null");
|
||||
|
||||
@@ -473,34 +430,10 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
|
||||
return doMultiSearch(multiSearchQueryParameters);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SearchHits<?>> multiSearch(List<? extends Query> queries, List<Class<?>> classes,
|
||||
List<IndexCoordinates> indexes) {
|
||||
|
||||
Assert.notNull(queries, "queries must not be null");
|
||||
Assert.notNull(classes, "classes must not be null");
|
||||
Assert.notNull(indexes, "indexes must not be null");
|
||||
Assert.isTrue(queries.size() == classes.size() && queries.size() == indexes.size(),
|
||||
"queries, classes and indexes must have the same size");
|
||||
|
||||
List<MultiSearchQueryParameter> multiSearchQueryParameters = new ArrayList<>(queries.size());
|
||||
Iterator<Class<?>> it = classes.iterator();
|
||||
Iterator<IndexCoordinates> indexesIt = indexes.iterator();
|
||||
|
||||
for (Query query : queries) {
|
||||
Class<?> clazz = it.next();
|
||||
IndexCoordinates index = indexesIt.next();
|
||||
multiSearchQueryParameters.add(new MultiSearchQueryParameter(query, clazz, index));
|
||||
}
|
||||
|
||||
return doMultiSearch(multiSearchQueryParameters);
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
private List<SearchHits<?>> doMultiSearch(List<MultiSearchQueryParameter> multiSearchQueryParameters) {
|
||||
|
||||
MsearchRequest request = requestConverter.searchMsearchRequest(multiSearchQueryParameters,
|
||||
routingResolver.getRouting());
|
||||
MsearchRequest request = requestConverter.searchMsearchRequest(multiSearchQueryParameters);
|
||||
|
||||
MsearchResponse<EntityAsMap> msearchResponse = execute(client -> client.msearch(request, EntityAsMap.class));
|
||||
List<MultiSearchResponseItem<EntityAsMap>> responseItems = msearchResponse.responses();
|
||||
@@ -543,58 +476,16 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
|
||||
/**
|
||||
* value class combining the information needed for a single query in a multisearch request.
|
||||
*/
|
||||
record MultiSearchQueryParameter(Query query, Class<?> clazz, IndexCoordinates index) {
|
||||
}
|
||||
static class MultiSearchQueryParameter {
|
||||
final Query query;
|
||||
final Class<?> clazz;
|
||||
final IndexCoordinates index;
|
||||
|
||||
@Override
|
||||
public String openPointInTime(IndexCoordinates index, Duration keepAlive, Boolean ignoreUnavailable) {
|
||||
|
||||
Assert.notNull(index, "index must not be null");
|
||||
Assert.notNull(keepAlive, "keepAlive must not be null");
|
||||
Assert.notNull(ignoreUnavailable, "ignoreUnavailable must not be null");
|
||||
|
||||
var request = requestConverter.searchOpenPointInTimeRequest(index, keepAlive, ignoreUnavailable);
|
||||
return execute(client -> client.openPointInTime(request)).id();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean closePointInTime(String pit) {
|
||||
|
||||
Assert.notNull(pit, "pit must not be null");
|
||||
|
||||
ClosePointInTimeRequest request = requestConverter.searchClosePointInTime(pit);
|
||||
var response = execute(client -> client.closePointInTime(request));
|
||||
return response.succeeded();
|
||||
}
|
||||
|
||||
// endregion
|
||||
|
||||
// region script methods
|
||||
@Override
|
||||
public boolean putScript(Script script) {
|
||||
|
||||
Assert.notNull(script, "script must not be null");
|
||||
|
||||
var request = requestConverter.scriptPut(script);
|
||||
return execute(client -> client.putScript(request)).acknowledged();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public Script getScript(String name) {
|
||||
|
||||
Assert.notNull(name, "name must not be null");
|
||||
|
||||
var request = requestConverter.scriptGet(name);
|
||||
return responseConverter.scriptResponse(execute(client -> client.getScript(request)));
|
||||
}
|
||||
|
||||
public boolean deleteScript(String name) {
|
||||
|
||||
Assert.notNull(name, "name must not be null");
|
||||
|
||||
DeleteScriptRequest request = requestConverter.scriptDelete(name);
|
||||
return execute(client -> client.deleteScript(request)).acknowledged();
|
||||
public MultiSearchQueryParameter(Query query, Class<?> clazz, IndexCoordinates index) {
|
||||
this.query = query;
|
||||
this.clazz = clazz;
|
||||
this.index = index;
|
||||
}
|
||||
}
|
||||
// endregion
|
||||
|
||||
@@ -660,8 +551,8 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
|
||||
failedDocuments);
|
||||
}
|
||||
|
||||
return bulkResponse.items().stream().map(
|
||||
item -> new IndexedObjectInformation(item.id(), item.index(), item.seqNo(), item.primaryTerm(), item.version()))
|
||||
return bulkResponse.items().stream()
|
||||
.map(item -> IndexedObjectInformation.of(item.id(), item.seqNo(), item.primaryTerm(), item.version()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2022-2023 the original author or authors.
|
||||
* Copyright 2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
+14
-113
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2021-2023 the original author or authors.
|
||||
* Copyright 2021-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -18,7 +18,6 @@ package org.springframework.data.elasticsearch.client.elc;
|
||||
import static org.springframework.util.StringUtils.*;
|
||||
|
||||
import co.elastic.clients.elasticsearch.indices.*;
|
||||
import co.elastic.clients.transport.ElasticsearchTransport;
|
||||
import co.elastic.clients.transport.endpoints.BooleanResponse;
|
||||
|
||||
import java.util.List;
|
||||
@@ -37,15 +36,15 @@ import org.springframework.data.elasticsearch.core.IndexOperations;
|
||||
import org.springframework.data.elasticsearch.core.ResourceUtil;
|
||||
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
|
||||
import org.springframework.data.elasticsearch.core.document.Document;
|
||||
import org.springframework.data.elasticsearch.core.index.*;
|
||||
import org.springframework.data.elasticsearch.core.index.DeleteIndexTemplateRequest;
|
||||
import org.springframework.data.elasticsearch.core.index.AliasActions;
|
||||
import org.springframework.data.elasticsearch.core.index.AliasData;
|
||||
import org.springframework.data.elasticsearch.core.index.DeleteTemplateRequest;
|
||||
import org.springframework.data.elasticsearch.core.index.ExistsIndexTemplateRequest;
|
||||
import org.springframework.data.elasticsearch.core.index.ExistsTemplateRequest;
|
||||
import org.springframework.data.elasticsearch.core.index.GetIndexTemplateRequest;
|
||||
import org.springframework.data.elasticsearch.core.index.GetTemplateRequest;
|
||||
import org.springframework.data.elasticsearch.core.index.PutIndexTemplateRequest;
|
||||
import org.springframework.data.elasticsearch.core.index.MappingBuilder;
|
||||
import org.springframework.data.elasticsearch.core.index.PutTemplateRequest;
|
||||
import org.springframework.data.elasticsearch.core.index.Settings;
|
||||
import org.springframework.data.elasticsearch.core.index.TemplateData;
|
||||
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity;
|
||||
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
|
||||
import org.springframework.lang.Nullable;
|
||||
@@ -57,42 +56,34 @@ import org.springframework.util.Assert;
|
||||
* @author Peter-Josef Meisch
|
||||
* @since 4.4
|
||||
*/
|
||||
public class IndicesTemplate extends ChildTemplate<ElasticsearchTransport, ElasticsearchIndicesClient>
|
||||
implements IndexOperations {
|
||||
public class IndicesTemplate extends ChildTemplate<ElasticsearchIndicesClient> implements IndexOperations {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(IndicesTemplate.class);
|
||||
|
||||
// we need a cluster client as well because ES has put some methods from the indices API into the cluster client
|
||||
// (component templates)
|
||||
private final ClusterTemplate clusterTemplate;
|
||||
protected final ElasticsearchConverter elasticsearchConverter;
|
||||
@Nullable protected final Class<?> boundClass;
|
||||
@Nullable protected final IndexCoordinates boundIndex;
|
||||
|
||||
public IndicesTemplate(ElasticsearchIndicesClient client, ClusterTemplate clusterTemplate,
|
||||
ElasticsearchConverter elasticsearchConverter, Class<?> boundClass) {
|
||||
public IndicesTemplate(ElasticsearchIndicesClient client, ElasticsearchConverter elasticsearchConverter,
|
||||
Class<?> boundClass) {
|
||||
super(client, elasticsearchConverter);
|
||||
|
||||
Assert.notNull(clusterTemplate, "cluster must not be null");
|
||||
Assert.notNull(elasticsearchConverter, "elasticsearchConverter must not be null");
|
||||
Assert.notNull(boundClass, "boundClass may not be null");
|
||||
|
||||
this.clusterTemplate = clusterTemplate;
|
||||
this.elasticsearchConverter = elasticsearchConverter;
|
||||
this.boundClass = boundClass;
|
||||
this.boundIndex = null;
|
||||
|
||||
}
|
||||
|
||||
public IndicesTemplate(ElasticsearchIndicesClient client, ClusterTemplate clusterTemplate,
|
||||
ElasticsearchConverter elasticsearchConverter, IndexCoordinates boundIndex) {
|
||||
public IndicesTemplate(ElasticsearchIndicesClient client, ElasticsearchConverter elasticsearchConverter,
|
||||
IndexCoordinates boundIndex) {
|
||||
super(client, elasticsearchConverter);
|
||||
|
||||
Assert.notNull(clusterTemplate, "cluster must not be null");
|
||||
Assert.notNull(elasticsearchConverter, "elasticsearchConverter must not be null");
|
||||
Assert.notNull(boundIndex, "boundIndex must not be null");
|
||||
|
||||
this.clusterTemplate = clusterTemplate;
|
||||
this.elasticsearchConverter = elasticsearchConverter;
|
||||
this.boundClass = null;
|
||||
this.boundIndex = boundIndex;
|
||||
@@ -196,6 +187,7 @@ public class IndicesTemplate extends ChildTemplate<ElasticsearchTransport, Elast
|
||||
Assert.notNull(clazz, "clazz must not be null");
|
||||
|
||||
// load mapping specified in Mapping annotation if present
|
||||
// noinspection DuplicatedCode
|
||||
Mapping mappingAnnotation = AnnotatedElementUtils.findMergedAnnotation(clazz, Mapping.class);
|
||||
|
||||
if (mappingAnnotation != null) {
|
||||
@@ -285,22 +277,12 @@ public class IndicesTemplate extends ChildTemplate<ElasticsearchTransport, Elast
|
||||
|
||||
@Override
|
||||
public Map<String, Set<AliasData>> getAliases(String... aliasNames) {
|
||||
|
||||
Assert.notNull(aliasNames, "aliasNames must not be null");
|
||||
|
||||
GetAliasRequest getAliasRequest = requestConverter.indicesGetAliasRequest(aliasNames, null);
|
||||
var getAliasResponse = execute(client -> client.getAlias(getAliasRequest));
|
||||
return responseConverter.indicesGetAliasData(getAliasResponse);
|
||||
throw new UnsupportedOperationException("not implemented");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Set<AliasData>> getAliasesForIndex(String... indexNames) {
|
||||
|
||||
Assert.notNull(indexNames, "indexNames must not be null");
|
||||
|
||||
GetAliasRequest getAliasRequest = requestConverter.indicesGetAliasRequest(null, indexNames);
|
||||
var getAliasResponse = execute(client -> client.getAlias(getAliasRequest));
|
||||
return responseConverter.indicesGetAliasData(getAliasResponse);
|
||||
throw new UnsupportedOperationException("not implemented");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -345,87 +327,6 @@ public class IndicesTemplate extends ChildTemplate<ElasticsearchTransport, Elast
|
||||
return execute(client -> client.deleteTemplate(deleteTemplateRequestES)).acknowledged();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean putIndexTemplate(PutIndexTemplateRequest putIndexTemplateRequest) {
|
||||
|
||||
co.elastic.clients.elasticsearch.indices.PutIndexTemplateRequest putIndexTemplateRequestES = requestConverter
|
||||
.indicesPutIndexTemplateRequest(putIndexTemplateRequest);
|
||||
|
||||
return execute(client -> client.putIndexTemplate(putIndexTemplateRequestES)).acknowledged();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean existsIndexTemplate(ExistsIndexTemplateRequest existsIndexTemplateRequest) {
|
||||
|
||||
Assert.notNull(existsIndexTemplateRequest, "existsIndexTemplateRequest must not be null");
|
||||
|
||||
co.elastic.clients.elasticsearch.indices.ExistsIndexTemplateRequest existsTemplateRequestES = requestConverter
|
||||
.indicesExistsIndexTemplateRequest(existsIndexTemplateRequest);
|
||||
return execute(client -> client.existsIndexTemplate(existsTemplateRequestES)).value();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<TemplateResponse> getIndexTemplate(GetIndexTemplateRequest getIndexTemplateRequest) {
|
||||
|
||||
Assert.notNull(getIndexTemplateRequest, "getIndexTemplateRequest must not be null");
|
||||
|
||||
co.elastic.clients.elasticsearch.indices.GetIndexTemplateRequest getIndexTemplateRequestES = requestConverter
|
||||
.indicesGetIndexTemplateRequest(getIndexTemplateRequest);
|
||||
var getIndexTemplateResponse = execute(client -> client.getIndexTemplate(getIndexTemplateRequestES));
|
||||
return responseConverter.getIndexTemplates(getIndexTemplateResponse);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteIndexTemplate(DeleteIndexTemplateRequest deleteIndexTemplateRequest) {
|
||||
|
||||
Assert.notNull(deleteIndexTemplateRequest, "deleteIndexTemplateRequest must not be null");
|
||||
|
||||
co.elastic.clients.elasticsearch.indices.DeleteIndexTemplateRequest deleteIndexTemplateRequestES = requestConverter
|
||||
.indicesDeleteIndexTemplateRequest(deleteIndexTemplateRequest);
|
||||
return execute(client -> client.deleteIndexTemplate(deleteIndexTemplateRequestES)).acknowledged();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean putComponentTemplate(PutComponentTemplateRequest putComponentTemplateRequest) {
|
||||
|
||||
Assert.notNull(putComponentTemplateRequest, "putComponentTemplateRequest must not be null");
|
||||
|
||||
co.elastic.clients.elasticsearch.cluster.PutComponentTemplateRequest putComponentTemplateRequestES = requestConverter
|
||||
.clusterPutComponentTemplateRequest(putComponentTemplateRequest);
|
||||
// the new Elasticsearch client has this call in the cluster index
|
||||
return clusterTemplate.execute(client -> client.putComponentTemplate(putComponentTemplateRequestES)).acknowledged();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean existsComponentTemplate(ExistsComponentTemplateRequest existsComponentTemplateRequest) {
|
||||
|
||||
Assert.notNull(existsComponentTemplateRequest, "existsComponentTemplateRequest must not be null");
|
||||
|
||||
co.elastic.clients.elasticsearch.cluster.ExistsComponentTemplateRequest existsComponentTemplateRequestES = requestConverter
|
||||
.clusterExistsComponentTemplateRequest(existsComponentTemplateRequest);
|
||||
return clusterTemplate.execute(client -> client.existsComponentTemplate(existsComponentTemplateRequestES)).value();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<TemplateResponse> getComponentTemplate(GetComponentTemplateRequest getComponentTemplateRequest) {
|
||||
|
||||
co.elastic.clients.elasticsearch.cluster.GetComponentTemplateRequest getComponentTemplateRequestES = requestConverter
|
||||
.clusterGetComponentTemplateRequest(getComponentTemplateRequest);
|
||||
var response = clusterTemplate.execute(client -> client.getComponentTemplate(getComponentTemplateRequestES));
|
||||
return responseConverter.clusterGetComponentTemplates(response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteComponentTemplate(DeleteComponentTemplateRequest deleteComponentTemplateRequest) {
|
||||
|
||||
Assert.notNull(deleteComponentTemplateRequest, "deleteComponentTemplateRequest must not be null");
|
||||
|
||||
co.elastic.clients.elasticsearch.cluster.DeleteComponentTemplateRequest deleteComponentTemplateRequestES = requestConverter
|
||||
.clusterDeleteComponentTemplateRequest(deleteComponentTemplateRequest);
|
||||
return clusterTemplate.execute(client -> client.deleteComponentTemplate(deleteComponentTemplateRequestES))
|
||||
.acknowledged();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<IndexInformation> getInformation(IndexCoordinates indexCoordinates) {
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user