├── .gitignore ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── lilium │ │ └── elasticsearch │ │ ├── ElasticsearchApplication.java │ │ ├── configuration │ │ └── Config.java │ │ ├── controller │ │ ├── IndexController.java │ │ ├── PersonController.java │ │ └── VehicleController.java │ │ ├── document │ │ ├── Person.java │ │ └── Vehicle.java │ │ ├── helper │ │ ├── Indices.java │ │ └── Util.java │ │ ├── repository │ │ └── PersonRepository.java │ │ ├── search │ │ ├── PagedRequestDTO.java │ │ ├── SearchRequestDTO.java │ │ └── util │ │ │ └── SearchUtil.java │ │ └── service │ │ ├── IndexService.java │ │ ├── PersonService.java │ │ ├── VehicleService.java │ │ └── helper │ │ └── VehicleDummyDataService.java └── resources │ ├── application.properties │ └── static │ ├── es-settings.json │ └── mappings │ └── vehicle.json └── test └── java └── com └── lilium └── elasticsearch └── ElasticsearchApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.5.0' 3 | id 'io.spring.dependency-management' version '1.0.11.RELEASE' 4 | id 'java' 5 | } 6 | 7 | group = 'com.lilium' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '15' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | implementation 'org.springframework.boot:spring-boot-starter-data-elasticsearch' 17 | implementation 'org.springframework.boot:spring-boot-starter-web' 18 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 19 | } 20 | 21 | test { 22 | useJUnitPlatform() 23 | } 24 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liliumbosniacum/elasticsearch/0b78726de3518be64d2c4150cf5ee334ec431d25/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'elasticsearch' 2 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/ElasticsearchApplication.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class ElasticsearchApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(ElasticsearchApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/configuration/Config.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch.configuration; 2 | 3 | import org.elasticsearch.client.RestHighLevelClient; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.ComponentScan; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.data.elasticsearch.client.ClientConfiguration; 9 | import org.springframework.data.elasticsearch.client.RestClients; 10 | import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration; 11 | import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; 12 | 13 | @Configuration 14 | @EnableElasticsearchRepositories(basePackages = "com.lilium.elasticsearch.repository") 15 | @ComponentScan(basePackages = {"com.lilium.elasticsearch"}) 16 | public class Config extends AbstractElasticsearchConfiguration { 17 | 18 | @Value("${elasticsearch.url}") 19 | public String elasticsearchUrl; 20 | 21 | @Bean 22 | @Override 23 | public RestHighLevelClient elasticsearchClient() { 24 | final ClientConfiguration config = ClientConfiguration.builder() 25 | .connectedTo(elasticsearchUrl) 26 | .build(); 27 | 28 | return RestClients.create(config).rest(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/controller/IndexController.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch.controller; 2 | 3 | import com.lilium.elasticsearch.service.IndexService; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.web.bind.annotation.PostMapping; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | @RestController 10 | @RequestMapping("/api/index") 11 | public class IndexController { 12 | private final IndexService service; 13 | 14 | @Autowired 15 | public IndexController(IndexService service) { 16 | this.service = service; 17 | } 18 | 19 | 20 | @PostMapping("/recreate") 21 | public void recreateAllIndices() { 22 | service.recreateIndices(true); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/controller/PersonController.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch.controller; 2 | 3 | import com.lilium.elasticsearch.document.Person; 4 | import com.lilium.elasticsearch.service.PersonService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.web.bind.annotation.*; 7 | 8 | @RestController 9 | @RequestMapping("/api/person") 10 | public class PersonController { 11 | private final PersonService service; 12 | 13 | @Autowired 14 | public PersonController(PersonService service) { 15 | this.service = service; 16 | } 17 | 18 | @PostMapping 19 | public void save(@RequestBody final Person person) { 20 | service.save(person); 21 | } 22 | 23 | @GetMapping("/{id}") 24 | public Person findById(@PathVariable final String id) { 25 | return service.findById(id); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/controller/VehicleController.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch.controller; 2 | 3 | import com.lilium.elasticsearch.document.Vehicle; 4 | import com.lilium.elasticsearch.search.SearchRequestDTO; 5 | import com.lilium.elasticsearch.service.VehicleService; 6 | import com.lilium.elasticsearch.service.helper.VehicleDummyDataService; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.format.annotation.DateTimeFormat; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import java.util.Date; 12 | import java.util.List; 13 | 14 | @RestController 15 | @RequestMapping("/api/vehicle") 16 | public class VehicleController { 17 | private final VehicleService service; 18 | private final VehicleDummyDataService dummyDataService; 19 | 20 | @Autowired 21 | public VehicleController(VehicleService service, VehicleDummyDataService dummyDataService) { 22 | this.service = service; 23 | this.dummyDataService = dummyDataService; 24 | } 25 | 26 | @PostMapping 27 | public void index(@RequestBody final Vehicle vehicle) { 28 | service.index(vehicle); 29 | } 30 | 31 | @PostMapping("/insertdummydata") 32 | public void insertDummyData() { 33 | dummyDataService.insertDummyData(); 34 | } 35 | 36 | @GetMapping("/{id}") 37 | public Vehicle getById(@PathVariable final String id) { 38 | return service.getById(id); 39 | } 40 | 41 | @PostMapping("/search") 42 | public List search(@RequestBody final SearchRequestDTO dto) { 43 | return service.search(dto); 44 | } 45 | 46 | @GetMapping("/search/{date}") 47 | public List getAllVehiclesCreatedSince( 48 | @PathVariable 49 | @DateTimeFormat(pattern = "yyyy-MM-dd") 50 | final Date date) { 51 | return service.getAllVehiclesCreatedSince(date); 52 | } 53 | 54 | @PostMapping("/searchcreatedsince/{date}") 55 | public List searchCreatedSince( 56 | @RequestBody final SearchRequestDTO dto, 57 | @PathVariable 58 | @DateTimeFormat(pattern = "yyyy-MM-dd") 59 | final Date date) { 60 | return service.searchCreatedSince(dto, date); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/document/Person.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch.document; 2 | 3 | import com.lilium.elasticsearch.helper.Indices; 4 | import org.springframework.data.annotation.Id; 5 | import org.springframework.data.elasticsearch.annotations.Document; 6 | import org.springframework.data.elasticsearch.annotations.Field; 7 | import org.springframework.data.elasticsearch.annotations.FieldType; 8 | import org.springframework.data.elasticsearch.annotations.Setting; 9 | 10 | @Document(indexName = Indices.PERSON_INDEX) 11 | @Setting(settingPath = "static/es-settings.json") 12 | public class Person { 13 | 14 | @Id 15 | @Field(type = FieldType.Keyword) 16 | private String id; 17 | 18 | @Field(type = FieldType.Text) 19 | private String name; 20 | 21 | public String getId() { 22 | return id; 23 | } 24 | 25 | public void setId(String id) { 26 | this.id = id; 27 | } 28 | 29 | public String getName() { 30 | return name; 31 | } 32 | 33 | public void setName(String name) { 34 | this.name = name; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/document/Vehicle.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch.document; 2 | 3 | import com.fasterxml.jackson.annotation.JsonFormat; 4 | 5 | import java.util.Date; 6 | 7 | public class Vehicle { 8 | private String id; 9 | private String number; 10 | private String name; 11 | @JsonFormat(pattern = "yyyy-MM-dd") 12 | private Date created; 13 | 14 | public String getId() { 15 | return id; 16 | } 17 | 18 | public void setId(String id) { 19 | this.id = id; 20 | } 21 | 22 | public String getNumber() { 23 | return number; 24 | } 25 | 26 | public void setNumber(String number) { 27 | this.number = number; 28 | } 29 | 30 | public String getName() { 31 | return name; 32 | } 33 | 34 | public void setName(String name) { 35 | this.name = name; 36 | } 37 | 38 | public Date getCreated() { 39 | return created; 40 | } 41 | 42 | public void setCreated(Date created) { 43 | this.created = created; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/helper/Indices.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch.helper; 2 | 3 | public final class Indices { 4 | 5 | public static final String PERSON_INDEX = "person"; 6 | public static final String VEHICLE_INDEX = "vehicle"; 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/helper/Util.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch.helper; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.core.io.ClassPathResource; 6 | 7 | import java.io.File; 8 | import java.nio.file.Files; 9 | 10 | public class Util { 11 | private static final Logger LOG = LoggerFactory.getLogger(Util.class); 12 | 13 | public static String loadAsString(final String path) { 14 | try { 15 | final File resource = new ClassPathResource(path).getFile(); 16 | 17 | return new String(Files.readAllBytes(resource.toPath())); 18 | } catch (final Exception e) { 19 | LOG.error(e.getMessage(), e); 20 | return null; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/repository/PersonRepository.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch.repository; 2 | 3 | import com.lilium.elasticsearch.document.Person; 4 | import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; 5 | 6 | public interface PersonRepository extends ElasticsearchRepository { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/search/PagedRequestDTO.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch.search; 2 | 3 | public class PagedRequestDTO { 4 | private static final int DEFAULT_SIZE = 100; 5 | 6 | private int page; 7 | private int size; 8 | 9 | public int getPage() { 10 | return page; 11 | } 12 | 13 | public void setPage(int page) { 14 | this.page = page; 15 | } 16 | 17 | public int getSize() { 18 | return size != 0 ? size : DEFAULT_SIZE; 19 | } 20 | 21 | public void setSize(int size) { 22 | this.size = size; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/search/SearchRequestDTO.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch.search; 2 | 3 | import org.elasticsearch.search.sort.SortOrder; 4 | 5 | import java.util.List; 6 | 7 | public class SearchRequestDTO extends PagedRequestDTO { 8 | private List fields; 9 | private String searchTerm; 10 | private String sortBy; 11 | private SortOrder order; 12 | 13 | public List getFields() { 14 | return fields; 15 | } 16 | 17 | public void setFields(List fields) { 18 | this.fields = fields; 19 | } 20 | 21 | public String getSearchTerm() { 22 | return searchTerm; 23 | } 24 | 25 | public void setSearchTerm(String searchTerm) { 26 | this.searchTerm = searchTerm; 27 | } 28 | 29 | public String getSortBy() { 30 | return sortBy; 31 | } 32 | 33 | public void setSortBy(String sortBy) { 34 | this.sortBy = sortBy; 35 | } 36 | 37 | public SortOrder getOrder() { 38 | return order; 39 | } 40 | 41 | public void setOrder(SortOrder order) { 42 | this.order = order; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/search/util/SearchUtil.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch.search.util; 2 | 3 | import com.lilium.elasticsearch.search.SearchRequestDTO; 4 | import org.elasticsearch.action.search.SearchRequest; 5 | import org.elasticsearch.index.query.*; 6 | import org.elasticsearch.search.builder.SearchSourceBuilder; 7 | import org.elasticsearch.search.sort.SortOrder; 8 | import org.springframework.util.CollectionUtils; 9 | 10 | import java.util.Date; 11 | import java.util.List; 12 | 13 | public final class SearchUtil { 14 | 15 | private SearchUtil() {} 16 | 17 | public static SearchRequest buildSearchRequest(final String indexName, 18 | final SearchRequestDTO dto) { 19 | try { 20 | final int page = dto.getPage(); 21 | final int size = dto.getSize(); 22 | final int from = page <= 0 ? 0 : page * size; 23 | 24 | SearchSourceBuilder builder = new SearchSourceBuilder() 25 | .from(from) 26 | .size(size) 27 | .postFilter(getQueryBuilder(dto)); 28 | 29 | if (dto.getSortBy() != null) { 30 | builder = builder.sort( 31 | dto.getSortBy(), 32 | dto.getOrder() != null ? dto.getOrder() : SortOrder.ASC 33 | ); 34 | } 35 | 36 | final SearchRequest request = new SearchRequest(indexName); 37 | request.source(builder); 38 | 39 | return request; 40 | } catch (final Exception e) { 41 | e.printStackTrace(); 42 | return null; 43 | } 44 | } 45 | 46 | public static SearchRequest buildSearchRequest(final String indexName, 47 | final String field, 48 | final Date date) { 49 | try { 50 | final SearchSourceBuilder builder = new SearchSourceBuilder() 51 | .postFilter(getQueryBuilder(field, date)); 52 | 53 | final SearchRequest request = new SearchRequest(indexName); 54 | request.source(builder); 55 | 56 | return request; 57 | } catch (final Exception e) { 58 | e.printStackTrace(); 59 | return null; 60 | } 61 | } 62 | 63 | public static SearchRequest buildSearchRequest(final String indexName, 64 | final SearchRequestDTO dto, 65 | final Date date) { 66 | try { 67 | final QueryBuilder searchQuery = getQueryBuilder(dto); 68 | final QueryBuilder dateQuery = getQueryBuilder("created", date); 69 | 70 | final BoolQueryBuilder boolQuery = QueryBuilders.boolQuery() 71 | .mustNot(searchQuery) 72 | .must(dateQuery); 73 | 74 | SearchSourceBuilder builder = new SearchSourceBuilder() 75 | .postFilter(boolQuery); 76 | 77 | if (dto.getSortBy() != null) { 78 | builder = builder.sort( 79 | dto.getSortBy(), 80 | dto.getOrder() != null ? dto.getOrder() : SortOrder.ASC 81 | ); 82 | } 83 | 84 | final SearchRequest request = new SearchRequest(indexName); 85 | request.source(builder); 86 | 87 | return request; 88 | } catch (final Exception e) { 89 | e.printStackTrace(); 90 | return null; 91 | } 92 | } 93 | 94 | private static QueryBuilder getQueryBuilder(final SearchRequestDTO dto) { 95 | if (dto == null) { 96 | return null; 97 | } 98 | 99 | final List fields = dto.getFields(); 100 | if (CollectionUtils.isEmpty(fields)) { 101 | return null; 102 | } 103 | 104 | if (fields.size() > 1) { 105 | final MultiMatchQueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(dto.getSearchTerm()) 106 | .type(MultiMatchQueryBuilder.Type.CROSS_FIELDS) 107 | .operator(Operator.AND); 108 | 109 | fields.forEach(queryBuilder::field); 110 | 111 | return queryBuilder; 112 | } 113 | 114 | return fields.stream() 115 | .findFirst() 116 | .map(field -> 117 | QueryBuilders.matchQuery(field, dto.getSearchTerm()) 118 | .operator(Operator.AND)) 119 | .orElse(null); 120 | } 121 | 122 | private static QueryBuilder getQueryBuilder(final String field, final Date date) { 123 | return QueryBuilders.rangeQuery(field).gte(date); 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/service/IndexService.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch.service; 2 | 3 | import com.lilium.elasticsearch.helper.Indices; 4 | import com.lilium.elasticsearch.helper.Util; 5 | import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; 6 | import org.elasticsearch.client.RequestOptions; 7 | import org.elasticsearch.client.RestHighLevelClient; 8 | import org.elasticsearch.client.indices.CreateIndexRequest; 9 | import org.elasticsearch.client.indices.GetIndexRequest; 10 | import org.elasticsearch.common.xcontent.XContentType; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.stereotype.Service; 15 | 16 | import javax.annotation.PostConstruct; 17 | import java.util.List; 18 | 19 | @Service 20 | public class IndexService { 21 | private static final Logger LOG = LoggerFactory.getLogger(IndexService.class); 22 | private static final List INDICES = List.of(Indices.VEHICLE_INDEX); 23 | private final RestHighLevelClient client; 24 | 25 | @Autowired 26 | public IndexService(RestHighLevelClient client) { 27 | this.client = client; 28 | } 29 | 30 | @PostConstruct 31 | public void tryToCreateIndices() { 32 | recreateIndices(false); 33 | } 34 | 35 | public void recreateIndices(final boolean deleteExisting) { 36 | final String settings = Util.loadAsString("static/es-settings.json"); 37 | 38 | if (settings == null) { 39 | LOG.error("Failed to load index settings"); 40 | return; 41 | } 42 | 43 | for (final String indexName : INDICES) { 44 | try { 45 | final boolean indexExists = client 46 | .indices() 47 | .exists(new GetIndexRequest(indexName), RequestOptions.DEFAULT); 48 | if (indexExists) { 49 | if (!deleteExisting) { 50 | continue; 51 | } 52 | 53 | client.indices().delete( 54 | new DeleteIndexRequest(indexName), 55 | RequestOptions.DEFAULT 56 | ); 57 | } 58 | 59 | final CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName); 60 | createIndexRequest.settings(settings, XContentType.JSON); 61 | 62 | final String mappings = loadMappings(indexName); 63 | if (mappings != null) { 64 | createIndexRequest.mapping(mappings, XContentType.JSON); 65 | } 66 | 67 | client.indices().create(createIndexRequest, RequestOptions.DEFAULT); 68 | } catch (final Exception e) { 69 | LOG.error(e.getMessage(), e); 70 | } 71 | } 72 | } 73 | 74 | private String loadMappings(String indexName) { 75 | final String mappings = Util.loadAsString("static/mappings/" + indexName + ".json"); 76 | if (mappings == null) { 77 | LOG.error("Failed to load mappings for index with name '{}'", indexName); 78 | return null; 79 | } 80 | 81 | return mappings; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/service/PersonService.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch.service; 2 | 3 | import com.lilium.elasticsearch.document.Person; 4 | import com.lilium.elasticsearch.repository.PersonRepository; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | 8 | @Service 9 | public class PersonService { 10 | 11 | private final PersonRepository repository; 12 | 13 | @Autowired 14 | public PersonService(PersonRepository repository) { 15 | this.repository = repository; 16 | } 17 | 18 | public void save(final Person person) { 19 | repository.save(person); 20 | } 21 | 22 | public Person findById(final String id) { 23 | return repository.findById(id).orElse(null); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/service/VehicleService.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch.service; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.lilium.elasticsearch.document.Vehicle; 5 | import com.lilium.elasticsearch.helper.Indices; 6 | import com.lilium.elasticsearch.search.SearchRequestDTO; 7 | import com.lilium.elasticsearch.search.util.SearchUtil; 8 | import org.elasticsearch.action.get.GetRequest; 9 | import org.elasticsearch.action.get.GetResponse; 10 | import org.elasticsearch.action.index.IndexRequest; 11 | import org.elasticsearch.action.index.IndexResponse; 12 | import org.elasticsearch.action.search.SearchRequest; 13 | import org.elasticsearch.action.search.SearchResponse; 14 | import org.elasticsearch.client.RequestOptions; 15 | import org.elasticsearch.client.RestHighLevelClient; 16 | import org.elasticsearch.common.xcontent.XContentType; 17 | import org.elasticsearch.rest.RestStatus; 18 | import org.elasticsearch.search.SearchHit; 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | import org.springframework.beans.factory.annotation.Autowired; 22 | import org.springframework.stereotype.Service; 23 | 24 | import java.util.ArrayList; 25 | import java.util.Collections; 26 | import java.util.Date; 27 | import java.util.List; 28 | 29 | @Service 30 | public class VehicleService { 31 | private static final ObjectMapper MAPPER = new ObjectMapper(); 32 | private static final Logger LOG = LoggerFactory.getLogger(VehicleService.class); 33 | 34 | private final RestHighLevelClient client; 35 | 36 | @Autowired 37 | public VehicleService(RestHighLevelClient client) { 38 | this.client = client; 39 | } 40 | 41 | /** 42 | * Used to search for vehicles based on data provided in the {@link SearchRequestDTO} DTO. For more info take a look 43 | * at DTO javadoc. 44 | * 45 | * @param dto DTO containing info about what to search for. 46 | * @return Returns a list of found vehicles. 47 | */ 48 | public List search(final SearchRequestDTO dto) { 49 | final SearchRequest request = SearchUtil.buildSearchRequest( 50 | Indices.VEHICLE_INDEX, 51 | dto 52 | ); 53 | 54 | return searchInternal(request); 55 | } 56 | 57 | /** 58 | * Used to get all vehicles that have been created since forwarded date. 59 | * 60 | * @param date Date that is forwarded to the search. 61 | * @return Returns all vehicles created since forwarded date. 62 | */ 63 | public List getAllVehiclesCreatedSince(final Date date) { 64 | final SearchRequest request = SearchUtil.buildSearchRequest( 65 | Indices.VEHICLE_INDEX, 66 | "created", 67 | date 68 | ); 69 | 70 | return searchInternal(request); 71 | } 72 | 73 | public List searchCreatedSince(final SearchRequestDTO dto, final Date date) { 74 | final SearchRequest request = SearchUtil.buildSearchRequest( 75 | Indices.VEHICLE_INDEX, 76 | dto, 77 | date 78 | ); 79 | 80 | return searchInternal(request); 81 | } 82 | 83 | private List searchInternal(final SearchRequest request) { 84 | if (request == null) { 85 | LOG.error("Failed to build search request"); 86 | return Collections.emptyList(); 87 | } 88 | 89 | try { 90 | final SearchResponse response = client.search(request, RequestOptions.DEFAULT); 91 | 92 | final SearchHit[] searchHits = response.getHits().getHits(); 93 | final List vehicles = new ArrayList<>(searchHits.length); 94 | for (SearchHit hit : searchHits) { 95 | vehicles.add( 96 | MAPPER.readValue(hit.getSourceAsString(), Vehicle.class) 97 | ); 98 | } 99 | 100 | return vehicles; 101 | } catch (Exception e) { 102 | LOG.error(e.getMessage(), e); 103 | return Collections.emptyList(); 104 | } 105 | } 106 | 107 | public Boolean index(final Vehicle vehicle) { 108 | try { 109 | final String vehicleAsString = MAPPER.writeValueAsString(vehicle); 110 | 111 | final IndexRequest request = new IndexRequest(Indices.VEHICLE_INDEX); 112 | request.id(vehicle.getId()); 113 | request.source(vehicleAsString, XContentType.JSON); 114 | 115 | final IndexResponse response = client.index(request, RequestOptions.DEFAULT); 116 | 117 | return response != null && response.status().equals(RestStatus.OK); 118 | } catch (final Exception e) { 119 | LOG.error(e.getMessage(), e); 120 | return false; 121 | } 122 | } 123 | 124 | public Vehicle getById(final String vehicleId) { 125 | try { 126 | final GetResponse documentFields = client.get( 127 | new GetRequest(Indices.VEHICLE_INDEX, vehicleId), 128 | RequestOptions.DEFAULT 129 | ); 130 | if (documentFields == null || documentFields.isSourceEmpty()) { 131 | return null; 132 | } 133 | 134 | return MAPPER.readValue(documentFields.getSourceAsString(), Vehicle.class); 135 | } catch (final Exception e) { 136 | LOG.error(e.getMessage(), e); 137 | return null; 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/main/java/com/lilium/elasticsearch/service/helper/VehicleDummyDataService.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch.service.helper; 2 | 3 | import com.lilium.elasticsearch.document.Vehicle; 4 | import com.lilium.elasticsearch.service.VehicleService; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.text.ParseException; 10 | import java.text.SimpleDateFormat; 11 | 12 | /** 13 | * Service used to insert some dummy data into vehicle index. 14 | * 15 | * @author mirza 16 | */ 17 | @Service 18 | public class VehicleDummyDataService { 19 | private static final Logger LOG = LoggerFactory.getLogger(VehicleDummyDataService.class); 20 | private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); 21 | 22 | private final VehicleService vehicleService; 23 | 24 | public VehicleDummyDataService(final VehicleService vehicleService) { 25 | this.vehicleService = vehicleService; 26 | } 27 | 28 | public void insertDummyData() { 29 | vehicleService.index(buildVehicle("1", "Audi A1", "AAA-123", "2010-01-01")); 30 | vehicleService.index(buildVehicle("2", "Audi A3", "AAB-123", "2011-07-05")); 31 | vehicleService.index(buildVehicle("3", "Audi A3", "AAC-123", "2012-10-03")); 32 | 33 | vehicleService.index(buildVehicle("4", "BMW M3", "AAA-023", "2021-10-06")); 34 | vehicleService.index(buildVehicle("5", "BMW 3", "1AA-023", "2001-10-01")); 35 | vehicleService.index(buildVehicle("6", "BMW M5", "12A-023", "1999-05-08")); 36 | 37 | vehicleService.index(buildVehicle("7", "VW Golf", "42A-023", "1991-04-08")); 38 | vehicleService.index(buildVehicle("8", "VW Passat", "18A-023", "2021-04-08")); 39 | 40 | vehicleService.index(buildVehicle("9", "Skoda Kodiaq", "28A-023", "2020-01-04")); 41 | vehicleService.index(buildVehicle("10", "Skoda Yeti", "88A-023", "2015-03-09")); 42 | } 43 | 44 | private static Vehicle buildVehicle(final String id, 45 | final String name, 46 | final String number, 47 | final String date) { 48 | Vehicle vehicle = new Vehicle(); 49 | vehicle.setId(id); 50 | vehicle.setName(name); 51 | vehicle.setNumber(number); 52 | try { 53 | vehicle.setCreated(DATE_FORMAT.parse(date)); 54 | } catch (ParseException e) { 55 | LOG.error(e.getMessage(), e); 56 | } 57 | 58 | return vehicle; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | elasticsearch.url=localhost:9200 2 | -------------------------------------------------------------------------------- /src/main/resources/static/es-settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "index": { 3 | 4 | } 5 | } -------------------------------------------------------------------------------- /src/main/resources/static/mappings/vehicle.json: -------------------------------------------------------------------------------- 1 | { 2 | "properties" : { 3 | "id": { 4 | "type": "keyword" 5 | }, 6 | "number": { 7 | "type": "text" 8 | }, 9 | "name": { 10 | "type": "text" 11 | }, 12 | "created": { 13 | "type": "date" 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /src/test/java/com/lilium/elasticsearch/ElasticsearchApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.lilium.elasticsearch; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class ElasticsearchApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | --------------------------------------------------------------------------------