首页 > kotlin + springboot启用elasticsearch搜索

kotlin + springboot启用elasticsearch搜索

参考自:

http://how2j.cn/k/search-engine/search-engine-springboot/1791.html?p=78908

工具版本: elasticsearch 6.2.2、 kibana 6.2.2,  下载地址: elasticsearch、kibana

下载demo

1、kotlin版springboot项目创建

访问https://start.spring.io/, 创建项目demo(maven + kotlin + springboot 2.1.7, 其他默认)。

添加web支持、elasticsearch搜索及kotlin测试所需依赖

        org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-data-elasticsearchorg.jetbrains.kotlinkotlin-test-junit51.2.70test

最终pom.xml文件为


xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">4.0.0org.springframework.bootspring-boot-starter-parent2.1.7.RELEASE com.exampledemo0.0.1-SNAPSHOTdemoDemo project for Spring Boot1.81.2.71org.springframework.bootspring-boot-starterorg.jetbrains.kotlinkotlin-reflectorg.jetbrains.kotlinkotlin-stdlib-jdk8org.springframework.bootspring-boot-starter-testtestorg.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-data-elasticsearchorg.jetbrains.kotlinkotlin-test-junit51.2.70test${project.basedir}/src/main/kotlin${project.basedir}/src/test/kotlinorg.springframework.bootspring-boot-maven-pluginorg.jetbrains.kotlinkotlin-maven-plugin-Xjsr305=strictspringorg.jetbrains.kotlinkotlin-maven-allopen${kotlin.version}
View Code

2、创建实体类Category.kt

package com.example.demo.entityimport org.springframework.data.elasticsearch.annotations.Document@Document(indexName = "test", type = "category")
class Category {var id : Int? = null;var name : String? = null;
}

es操作dao类CategoryESDAO.kt

package com.example.demo.esimport com.example.demo.entity.Category
import org.springframework.data.elasticsearch.repository.ElasticsearchRepositoryinterface CategoryESDAO : ElasticsearchRepository

创建类SearchController.kt,并实现搜索方法,这里根据keyword作为前缀进行搜索

package com.example.demo.controllerimport com.example.demo.entity.Category
import com.example.demo.es.CategoryESDAO
import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery
import org.elasticsearch.index.query.QueryBuilders
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import javax.annotation.Resource@RestController
class SearchController {@Resourceprivate lateinit var categoryESDAO: CategoryESDAO@GetMapping("/search")fun search(@RequestParam(value = "keyword") keyword: String, @RequestParam(value = "start", defaultValue = "0") start: Int,@RequestParam(value = "size", defaultValue = "5") size: Int): List {val queryBuilder = QueryBuilders.matchPhrasePrefixQuery("name", keyword)val sort = Sort(Sort.Direction.DESC, "id")val pageable = PageRequest.of(start, size, sort)val searchQuery = NativeSearchQueryBuilder().withPageable(pageable).withQuery(queryBuilder).build()val page = categoryESDAO.search(searchQuery)return page.content.filter {category ->  category != null}.toList()}}

在类DemoApplication.kt中指定包名,

package com.example.demoimport org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories@SpringBootApplication
@EnableElasticsearchRepositories(basePackages = ["com.example.demo.es"])
class DemoApplicationfun main(args: Array) {runApplication(*args)
}

在resources目录下application.properties中增加elasticsearch的参数

#ElasticSearch
spring.data.elasticsearch.cluster-nodes = 127.0.0.1:9300

3、创建测试类

在test/kotlin目录下com.example.demo包下创建类TestSearchController.kt测试搜索

package com.example.demoimport com.example.demo.entity.Category
import com.example.demo.es.CategoryESDAO
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.HttpMethod
import org.springframework.test.context.web.WebAppConfiguration
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
import org.springframework.test.web.servlet.setup.MockMvcBuilders
import org.springframework.web.context.WebApplicationContext
import javax.annotation.Resource@SpringBootTest
@WebAppConfiguration
class TestSearchController {@Resourceprivate lateinit var wac : WebApplicationContext@Resourceprivate lateinit var categoryESDAO: CategoryESDAO@BeforeEachfun add() {for (ch in 'a'..'z') {val category = Category()category.id = ch - 'a'category.name = ch.toUpperCase().toString().plus(ch)categoryESDAO.save(category)}}@Testfun test() {val mockMvc = MockMvcBuilders.webAppContextSetup(wac).build()val result = mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.GET, "/search?keyword=Aa")).andExpect(MockMvcResultMatchers.status().isOk).andDo(::println).andReturn().response.contentAsString;println(result)}
}

依次启动elasticsearch6.2.2、kibana6.2.2,

在浏览器中打开http://localhost:5601/app/kibana#/dev_tools/console?_g=()

执行

PUT test

创建test(对应Category类Document注解 indexName)索引,然后执行TestSearchController类进行测试,

控制台输出结果为:

[{"id":0,"name":"Aa"}]

 

转载于:https://www.cnblogs.com/wushengwuxi/p/11349523.html

更多相关: