Spring Boot and Kotlin integrate full text search engine Elasticsearch sample code

  • 2021-01-06 00:36:55
  • OfStack

ES1en is almost unbeatable in full-text search, and is also very useful in big data. It can be used as ES2en (which was originally ES3en).

This article provides a brief introduction to Spring Boot using Kotlin to connect to Elasticsearch. But doesn't do very detailed introduction, if you want to understand Elasticsearch Java/kotlin in use, please refer to my previous written "Elasticsearch Java API manual https: / / gitee com quanke/elasticsearch java/used as an example, it contains contains we tread with craters.

If you don't know Elasticsearch at all, please understand it first and install the Elasticsearch service

There are several ways to connect Elasticsearch

Spring Data Elasticsearch elasticsearch Java client Other third party libraries

It should be noted that if using Spring Data Elasticsearch, spring 1.5++ version of boot does not support the latest version of elasticsearch.

spring data elasticsearch and elasticsearch versions are listed below

spring data elasticsearch elasticsearch
3.0.0.RC2 5.5.0
3.0.0.M4 5.4.0
2.0.4.RELEASE 2.4.0
2.0.0.RELEASE 2.2.0
1.4.0.M1 1.7.3
1.3.0.RELEASE 1.5.2
1.2.0.RELEASE 1.4.4
1.1.0.RELEASE 1.3.2
1.0.0.RELEASE 1.1.1

We use Elasticsearch version 5.5.6, spring boot version 1.5.6 and spring data elasticsearch supports versions above Elasticsearch5.0, elasticsearch is not RELEASE version, data is not RELEASE version All we use is elasticsearch Java client way, but now the official recommend better way can refer me to write the Elasticsearch Java Rest API manual https: / / gitee com quanke/elasticsearch - java - rest, but this article or use elasticsearch Java client

Build Spring Boot Kotlin project

If you have problems with your build project, you can refer to my previous article "Creating RESTfull API with Spring Boot and Kotlin".

Built using Gradle, added in file build.gradle


dependencies {
 compile "org.elasticsearch:elasticsearch:$elasticsearch_version"
 compile "org.elasticsearch.client:transport:$elasticsearch_version"
}

The complete build.gradle file


group 'name.quanke.kotlin'
version '1.0-SNAPSHOT'
buildscript {
 ext.kotlin_version = '1.2.10'
 ext.spring_boot_version = '1.5.4.RELEASE'
 ext.springfox_swagger2_version = '2.7.0'
 ext.mysql_version = '5.1.21'
 ext.mybatis_version = '1.1.1'
 ext.elasticsearch_version = '5.5.1'
 ext.fastjson_version = '1.2.7'
 repositories {
  mavenCentral()
 }
 dependencies {
  classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  classpath("org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version")

//  Kotlin integration SpringBoot The default no-argument constructor, which sets all classes by default open Class plug-in 
  classpath("org.jetbrains.kotlin:kotlin-noarg:$kotlin_version")
  classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlin_version")
 }
}

apply plugin: 'kotlin'
apply plugin: "kotlin-spring" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin
apply plugin: 'org.springframework.boot'
apply plugin: "kotlin-jpa" //https://stackoverflow.com/questions/32038177/kotlin-with-jpa-default-constructor-hell
jar {
 baseName = 'chapter11-6-8-service'
 version = '0.1.0'
}
repositories {
 mavenCentral()
}

dependencies {
 compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
 compile("org.jetbrains.kotlin:kotlin-reflect:${kotlin_version}")
 compile "org.springframework.boot:spring-boot-starter-web:$spring_boot_version"
 compile "org.elasticsearch:elasticsearch:$elasticsearch_version"
 compile "org.elasticsearch.client:transport:$elasticsearch_version"
 compile "com.alibaba:fastjson:$fastjson_version"
 compile "org.apache.commons:commons-lang3:3.6"
 testCompile "org.springframework.boot:spring-boot-starter-test:$spring_boot_version"
 testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"

}

compileKotlin {
 kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
 kotlinOptions.jvmTarget = "1.8"
}

Write the test base class ElasticsearchClient first


import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.serializer.SerializerFeature
import org.elasticsearch.action.search.SearchResponse
import org.elasticsearch.client.transport.TransportClient
import org.elasticsearch.common.settings.Settings
import org.elasticsearch.common.transport.InetSocketTransportAddress
import org.elasticsearch.transport.client.PreBuiltTransportClient
import org.junit.After
import org.junit.Before
import java.net.InetAddress

/**
 * Elasticsearch 5.5.1  the client  and  ElasticsearchTemplate The initialization 
 *  As a 1 An external visitor, request ES For a cluster, it is 1 External factors. 
 * Created by http://quanke.name on 2017/11/10.
 */
open class ElasticsearchClient {

 protected var client: TransportClient? = null
 @Before
 @Throws(Exception::class)
 fun setUp() {
  val esSettings = Settings.builder()
    .put("cluster.name", "utan-es") // Set up the ES Name of the instance 
    .put("client.transport.sniff", true) // Automatically sniffs the status of the entire cluster and puts others in the cluster ES The node's ip Add to the local client list 
    .build()

  /**
   *  The connection mode here means no installation x-pack The plug-in , If it is installed x-pack The reference  [ElasticsearchXPackClient]
   * 1. java The client-side approach is tcp The agreement 9300 Port for communication 
   * 2. http The client-side approach is http The agreement 9200 Port for communication 
   */
  client = PreBuiltTransportClient(esSettings)
    .addTransportAddress(InetSocketTransportAddress(InetAddress.getByName("192.168.1.10"), 9300))

  println("ElasticsearchClient  The connection is successful ")
 }

 @After
 @Throws(Exception::class)
 fun tearDown() {
  if (client != null) {
   client!!.close()
  }

 }

 protected fun println(searchResponse: SearchResponse) {
  val searchHits = searchResponse.hits.hits
  for (searchHit in searchHits) {
   println(JSON.toJSONString(searchHit.source, SerializerFeature.PrettyFormat))
  }
 }
}

Run unit tests


import org.elasticsearch.index.query.QueryBuilders.matchAllQuery
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
/**
 * Created by http://quanke.name on 2018/1/9.
 */
@RunWith(SpringRunner::class)
@SpringBootTest
class ApplicationTests : ElasticsearchClient() {

 @Test
 fun `es test"`() {
  val qb = matchAllQuery()
  val response = client!!.prepareSearch("twitter")// It can be multiple index
    .setTypes("tweet")// It can be of multiple types 
    .setQuery(qb) // Query  Query conditions 
    .get()
  println(response)
 }
}

- dayu-spring-boot-starter-es -es - dayu-spring-boot-starter-es


Related articles: