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
1、kotlin版springboot项目创建
访问https://start.spring.io/, 创建项目demo(maven + kotlin + springboot 2.1.7, 其他默认)。
添加web支持、elasticsearch搜索及kotlin测试所需依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-elasticsearch -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency> <!-- https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-test-junit5 -->
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test-junit5</artifactId>
<version>1.2.70</version>
<scope>test</scope>
</dependency>
最终pom.xml文件为
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
<kotlin.version>1.2.71</kotlin.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-elasticsearch -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency> <!-- https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-test-junit5 -->
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test-junit5</artifactId>
<version>1.2.70</version>
<scope>test</scope>
</dependency>
</dependencies> <build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build> </project>
2、创建实体类Category.kt
package com.example.demo.entity import 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.es import com.example.demo.entity.Category
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository interface CategoryESDAO : ElasticsearchRepository<Category, Int>
创建类SearchController.kt,并实现搜索方法,这里根据keyword作为前缀进行搜索
package com.example.demo.controller import 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 { @Resource
private 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<Category> {
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.demo import 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 DemoApplication fun main(args: Array<String>) {
runApplication<DemoApplication>(*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.demo import 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 { @Resource
private lateinit var wac : WebApplicationContext @Resource
private lateinit var categoryESDAO: CategoryESDAO @BeforeEach
fun add() {
for (ch in 'a'..'z') {
val category = Category()
category.id = ch - 'a'
category.name = ch.toUpperCase().toString().plus(ch)
categoryESDAO.save(category)
}
} @Test
fun 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"}]
kotlin + springboot启用elasticsearch搜索的更多相关文章
- springBoot配置elasticsearch搜索
1.本地安装elasticsearch服务,具体过程见上一篇文章(安装和配置elasticsearch服务集群) 2.修改项目中pom文件,引入搜索相关jar包 <!-- elasticsear ...
- SpringBoot整合ElasticSearch实现多版本的兼容
前言 在上一篇学习SpringBoot中,整合了Mybatis.Druid和PageHelper并实现了多数据源的操作.本篇主要是介绍和使用目前最火的搜索引擎ElastiSearch,并和Spring ...
- springboot集成elasticsearch
在基础阶段学习ES一般是首先是 安装ES后借助 Kibana 来进行CURD 了解ES的使用: 在进阶阶段可以需要学习ES的底层原理,如何通过Version来实现乐观锁保证ES不出问题等核心原理: 第 ...
- ElasticSearch(2)---SpringBoot整合ElasticSearch
SpringBoot整合ElasticSearch 一.基于spring-boot-starter-data-elasticsearch整合 开发环境:springboot版本:2.0.1,elast ...
- 一次 ElasticSearch 搜索优化
一次 ElasticSearch 搜索优化 1. 环境 ES6.3.2,索引名称 user_v1,5个主分片,每个分片一个副本.分片基本都在11GB左右,GET _cat/shards/user 一共 ...
- ElasticSearch搜索介绍四
ElasticSearch搜索 最基础的搜索: curl -XGET http://localhost:9200/_search 返回的结果为: { "took": 2, &quo ...
- springboot整合elasticsearch入门例子
springboot整合elasticsearch入门例子 https://blog.csdn.net/tianyaleixiaowu/article/details/72833940 Elastic ...
- Elasticsearch搜索结果返回不一致问题
一.背景 这周在使用Elasticsearch搜索的时候遇到一个,对于同一个搜索请求,会出现top50返回结果和排序不一致的问题.那么为什么会出现这样的问题? 后来通过百度和google,发现这是因为 ...
- Springboot整合elasticsearch以及接口开发
Springboot整合elasticsearch以及接口开发 搭建elasticsearch集群 搭建过程略(我这里用的是elasticsearch5.5.2版本) 写入测试数据 新建索引book( ...
随机推荐
- F4NNIU 的常用 Linux 命令(2019-08-24)
目录 F4NNIU 的常用 Linux 命令 停止防火墙 查看 IP 址 启动 deepin 的桌面 查看当前时区 查看 CPU 和内存信息 用户相关 日志 F4NNIU 的常用 Linux 命令 记 ...
- oracle函数 LPAD(c1,n[,c2])
[功能]在字符串c1的左边用字符串c2填充,直到长度为n时为止 [参数]C1 字符串 n 追加后字符总长度 c2 追加字符串,默认为空格 [返回]字符型 [说明]如果c1长度大于n,则返回c1左边n个 ...
- H3C 常用信息查看命令
- 为什么有时候Css样式表某个属性引用不成功?
首次使用博客,很多东西都在探索,第一篇文章也不知道发布点什么,就随便写写,是在word里面写的,也懒得排版,将就这用吧. 闲着没事找了酷狗的API写了个简单的静态网页,完成了搜索,展示,播放功能.就想 ...
- hdu 1045 Fire Net(dfs)
Fire Net Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Su ...
- P1113 同颜色询问
题目描述 现在有一个包含 \(n\) 个元素的数组,它的元素的编号从 \(1\) 到 \(n\) . 每一个元素都有一个初始的颜色 \(C_i\) 以及数值 \(W_i\) . 这个数组支持 \(4\ ...
- 从规则引擎到复杂事件处理(CEP)
Drools Fusion既是规则引擎,又可以作为CEP.除了事件定义和时间推理之外,对于引擎本身也会有一些不同的使用.主要体现在会话时钟.流模式.滑动窗口和对事件的内存管理. 会话时钟 由于事件的时 ...
- poj 3624 Charm Bracelet(01背包)
Charm Bracelet Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 29295 Accepted: 13143 ...
- element-ui-——el-uploadexcel导入
布局文件:(选择文件放在了弹框内部——即点击导入按钮后弹框显示,先下载模板再选择文件点击提交按钮才上传) )) { this.$notify({ message: '数据导入成功', type: 's ...
- nginx+tomcat实现负载均衡(windows环境)
一.准备工作 nginx1.14 nginx1.14下载链接 tomcat8 tomcat8下载链接 windows系统 二.实现目标 访问http://localhost地址时, 将请求轮询到tom ...