前文中我们已经安装好了3台Elasticsearch,所以今天我们直接使用就好
1 quickstart 的骨架
可以再 start.spring.io 生成一个springboot工程
2 pom依赖
<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>
<groupId>com.arno</groupId>
<artifactId>springboot-elasticsearch</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-elasticsearch</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath>/</relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.5.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.5.2</version>
</dependency>
</dependencies>
</project>
如果报异常ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console…
添加下面两个jar即可,如果不添加也不会影响功能,
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.10.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.10.0</version>
</dependency>
3 application.properties
注意端口是9300不是http.port: 9200端口
server.port=8090
server.context-path=/
//集群名称,按照elasticsearch.yml里面的cluster.name: elasticsearch 进行填写
cluster-name=elasticsearch
//集群的地址,按照elasticsearch.yml里面的network.host: 192.168.1.55 进行填写,注意端口是9300不是http.port端口
//多个集群节点用,号分开
cluster-nodes=192.168.1.55:9300
4 启动类
启动类
package com.arno;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 当前类就是整个工程的入口,
* 所以编写main方法就在此
* @author Administrator
*
*/
@SpringBootApplication
public class StarterA {
/*
* main方法,是整个工程入口,入口进入后,通过当前
* 工程的类名,进行各种自动配置的开始,这里需要加载一个
* SpringApplication.run
*/
public static void main(String[] args) {
SpringApplication.run(StarterA.class, args);
}
}
config类
package com.arno.config;
import java.net.InetAddress;
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.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//此类会在springboot启动的时候执行,
//创建TransportClient 并初始化之后交给Spring管理
@Configuration
public class ESConfig {
//此处读取application.properties里面的配置文件
@Value("${cluster-name}")
private String name;
@Value("${cluster-nodes}")
private String nodes;
//初始化方法
@Bean
public TransportClient init(){
//设置cluster.name为我们配置文件中定义好的名字
Settings setting=Settings.builder()
.put("cluster.name", name).build();
//配置对象Setting,测试使用默认empty
TransportClient client=
new PreBuiltTransportClient(setting);
try{//连接指定集群名称的集群 elasticsearch
//如果是集群模式,需要将所有的主节点信息传递添加,我这里赖得写其他的集群。所以直接在配置文件添加就好
String[] hostAndPort=nodes.split(",");
for (String node : hostAndPort) {
String host=node.split(":")[0];
int port=Integer.parseInt(node.split(":")[1]);
client.addTransportAddress(
new InetSocketTransportAddress(
InetAddress.getByName(host),port));
}
}catch(Exception e){
e.printStackTrace();
}
return client;
}
}
Controller类
package com.arno.controller;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
//利用TransportClient搜索数据
//因为config中已经交给spring管理,所以此处可以自己注入
@Autowired
private TransportClient client;
@RequestMapping("searcher")
@ResponseBody
public String queryProductName(String name){
//构造一个matchquery对象
//name是域名,
//text查询参数文本,进行分词计算
MatchQueryBuilder query = QueryBuilders.matchQuery("product_name", name).
operator(Operator.AND);
//java编程思想-->java,编,程,思,想
SearchResponse response = client.prepareSearch("index02").setQuery(query).
setFrom(0).setSize(10).get();
//从response中遍历
SearchHits hits = response.getHits();
System.out.println("供收到总数据:"+hits.getTotalHits());
String result="";
for (SearchHit hit : hits) {
result=result+hit.getSource().
get("product_description");
}
return result;
}
}
查询测试
因为之前我们已经通过Logstash把数据库中的数据导入到index02索引中,所以我们之间按照关键词进行查询即可
http://localhost:8090/searcher?name=关键词
这里会把关键词进行分词,然后再去查询索引,之后按照逻辑进行处理即可