近几篇ElasticSearch系列:

1、阿里云服务器Linux系统安装配置ElasticSearch搜索引擎

2、Linux系统中ElasticSearch搜索引擎安装配置Head插件

3、ElasticSearch搜索引擎安装配置中文分词器IK插件

4、ElasticSearch搜索引擎安装配置拼音插件pinyin

5、ElasticSearch搜索引擎在JavaWeb项目中的应用

一、前言

前四篇简单介绍了ElasticSearch(以下简称ES)在阿里云服务器Linux系统上的部署配置等。本篇将简述一下ES在JavaWeb项目中的应用。本项目前端框架是Vue.js,前后端数据交互采用是常用的SSM框架,项目管理工具为Maven,ES为6.3.2版本。

二、正文

1、ES在Maven中添加相应依赖,如下所示:

 <dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.3.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.3.2</version>
</dependency>

2、@Configuration注解新建的 “ElasticSearchConfig” 类,用来初始化ES客户端TransportClient连接,通过setting来创建,若不指定则默认链接的集群名为elasticsearch,如下图所示:

 @Configuration
public class ElasticSearchConfig { @Bean
public TransportClient client() throws UnknownHostException {
Settings settings = Settings.builder().build();
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName("部署ES的IP地址"), 9300));
return client;
}
}

3、jsp里首先需要导入jquery与Vue,然后css样式仅供参考,如下图所示:

 <div id="search_main" style="position: relative;top: -360px;left: -200px;width: 100%;height: 50px;text-align: center">
<input id="search_input1" type="text" name="search1" placeholder="请输入企业名称。如“阿里巴巴”或“alibaba”"
style="height: 50px;width: 720px;border: none;font-size: 18px;" onkeypress="EnterPress(event)" onkeydown="EnterPress()"
v-model="searchText" v-on:keyup="showName(searchText)"/>
<img id="voice" src="icon/voice1.png" width="35" height="35" style="position: absolute;left: 1145px;top: 7px;"/>
<button id="search_button1" type="button" style="position: relative;left: -4px;top: 1px;height: 50px;width: 100px;border: none;background-color: #1db5ee">
<font size="4" color="white" style="align-content: center">搜索</font>
</button>
<font id="searchType" style="display: none">企业名</font>
<div id="parentRelationSearch" v-for="(company, cIndex) in companyList" style="position: relative;top: 0px;left: 474px;height: auto;width: 719px;background-color: #ffffff;z-index: 99">
<div class="relationSearch" v-on:click="putVal(company.name)" v-on:mouseenter="mouseEnter($event)" v-on:mouseleave="mouseLeave($event)" style="position: relative;top: 0px;left: 0px;width: 100%;height: 35px;border-bottom: 1px solid #e8e8e8;line-height: 35px;">
<font size="2" style="position: absolute;left: 5px">{{company.name}}</font>
<font size="1.5" style="position: absolute;left: 92%;">{{company.score}}</font>
</div>
</div>
</div>

4、id为search_main的元素为Vue实例挂载的元素节点,以及showName函数(ajax请求)为keyup事件,putVal函数(将用户选中的元素值赋值给搜索框)为click事件,mouseEnter、mouseLeave函数分别为mouseenter、mouseleave事件,如下图所示:

 var vm1 = new Vue({
el: '#search_main',
data: {
searchText: "",
companyList: [],
},
mounted: function () {
this.showName();
this.putVal();
this.mouseEnter();
this.mouseLeave();
},
methods: {
putVal: function (val) {
$("#search_input1").val(val);
$(".relationSearch").hide();
document.getElementById("search_input1").focus();
},
showName: function (key) {
console.log(key);
if (key.length != 0) {
var searchType = document.getElementById("searchType").innerText;
if (searchType == "全部" || searchType == "企业名") {
$(".relationSearch").show();
var _this = this;
this.$http.get("auto_think.do?key=" + key).then(function (jsonResult) {
_this.companyList = (jsonResult.body);
});
}
} else {
$(".relationSearch").hide();
}
},
mouseEnter: function ($event) {
$event.currentTarget.className = "relationSearch searchActive";
},
mouseLeave: function ($event) {
$event.currentTarget.className = "relationSearch";
}
}
});

上述mouseEnter函数是用于动态添加class,用以实现鼠标移入则修改元素的背景功能:

 .searchActive{
background-color:#e8e8e8;
}

5、QueryBuilder是ES提供的一个查询接口,进行单个匹配值为key的文档。SearchRequestBuilder根据索引与类型构造查询请求,设置查询条件和分页参数,再获取返回值并进行处理,最后返回,如下图所示:

 package controller;

 import entity.ElasticSearchResult;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
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.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List; @Controller
public class ElasticSearchController { @Autowired
private TransportClient client; //搜索自动联想
@GetMapping("/auto_think.do")
@ResponseBody
public List<ElasticSearchResult> findIndexRecordByName(@RequestParam(name = "key") String key) {
// 构造查询请求
QueryBuilder bq = QueryBuilders.matchQuery("name.pinyin", key);
SearchRequestBuilder searchRequest = client.prepareSearch("medcl").setTypes("folks"); // 设置查询条件和分页参数
int start = 0;
int size = 5;
searchRequest.setQuery(bq).setFrom(start).setSize(size); // 获取返回值,并进行处理
SearchResponse response = searchRequest.execute().actionGet();
SearchHits shs = response.getHits();
List<ElasticSearchResult> esResultList = new ArrayList<>();
for (SearchHit hit : shs) {
ElasticSearchResult esResult = new ElasticSearchResult();
double score = hit.getScore();
BigDecimal b = new BigDecimal(score);
score = b.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
String name = (String) hit.getSourceAsMap().get("name");
System.out.println("score:" + score + "name:" + name);
esResult.setScore(score);
esResult.setName(name);
esResultList.add(esResult);
}
return esResultList;
} }

下述为ElasticSearchResult实体类:

 package entity;

 public class ElasticSearchResult {

     private double score;

     private String name;

     public ElasticSearchResult() {
} public double getScore() {
return score;
} public void setScore(double score) {
this.score = score;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}

再附上向指定索引与类型添加、删除、更新文档函数代码,如下所示:

 /**
* 添加文档
* @param name
*/
public void addByName(String name) {
try {
XContentBuilder content = XContentFactory.jsonBuilder()
.startObject().field("name", name).endObject();
client.prepareIndex("medcl", "folks")
.setSource(content).get();
System.out.println("ElasticSearch添加文档成功。");
} catch (IOException e) {
System.out.println("ElasticSearch添加文档出错。");
e.printStackTrace();
}
} /**
* 删除文档
* @param name
*/
public void deleteByName(String name) {
BulkRequestBuilder bulkRequest = client.prepareBulk();
SearchResponse response = client.prepareSearch("medcl").setTypes("folks")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(QueryBuilders.termQuery("name", name))
.setFrom(0).setSize(20).setExplain(true).execute().actionGet();
for(SearchHit hit : response.getHits()){
String id = hit.getId();
bulkRequest.add(client.prepareDelete("medcl", "folks", id).request());
}
BulkResponse bulkResponse = bulkRequest.get(); if (bulkResponse.hasFailures()) {
System.out.println("ElasticSearch删除文档出错。");
for(BulkItemResponse item : bulkResponse.getItems()){
System.out.println(item.getFailureMessage());
}
}else {
System.out.println("ElasticSearch删除文档成功。");
}
} /**
* 更新文档
* @param beforeName
* @param afterName
*/
public void updateByName(String beforeName,String afterName){
SearchResponse response = client.prepareSearch("medcl").setTypes("folks")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(QueryBuilders.termQuery("name", beforeName))
.setFrom(0).setSize(20).setExplain(true).execute().actionGet();
try {
for(SearchHit hit : response.getHits()){
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index("medcl");
updateRequest.type("folks");
updateRequest.id(hit.getId());
updateRequest.doc(XContentFactory.jsonBuilder().startObject().field("name",afterName).endObject());
client.update(updateRequest).get();
}
System.out.println("ElasticSearch更新文档成功。");
}catch (Exception e){
System.out.println("ElasticSearch更新文档出错。");
e.printStackTrace();
}
}

最后附上功能演示效果图,如下图所示:

至此是对ElasticSearch搜索引擎在JavaWeb项目中的应用的一个简单介绍。

如有疏漏错误之处,还请不吝赐教!

ElasticSearch搜索引擎在JavaWeb项目中的应用的更多相关文章

  1. log4j在javaWeb项目中的使用

    在前边的文章中对log4j的配置文件进行了说明,今天介绍如何在普通的javaWeb项目中使用log4j. 在日常的开发过程中,日志使用的很频繁,我们可以利用日志来跟踪程序的错误,程序运行时的输出参数等 ...

  2. Druid使用起步—在javaWeb项目中配置监控 连接池

    当我们在javaWEB项目中使用到druid来作为我们的连接池的时候,一定不会忘了添加监控功能.下面我们就来看一下,在一个简单的web项目中(尚未使用任何框架)我们是如果来配置我们的web.xml来完 ...

  3. JavaWeb 项目中的绝对路径和相对路径以及问题的解决方式

    近期在做JavaWeb项目,总是出现各种的路径错误,并且发现不同情况下 /  所代表的含义不同,导致在调试路径上浪费了大量时间. 在JavaWeb项目中尽量使用绝对路径  由于使用绝对路径是绝对不会出 ...

  4. JavaWeb项目中web.xml有关servlet的基本配置

    JavaWeb项目中web.xml有关servlet的基本配置: 我们注意到,tomcat下的conf中也有一个web.xml文件,没错的,所有的JavaWeb项目中web.xml都继承自服务器下的w ...

  5. 关联分析FPGrowth算法在JavaWeb项目中的应用

    关联分析(关联挖掘)是指在交易数据.关系数据或其他信息载体中,查找存在于项目集合或对象集合之间的频繁模式.关联.相关性或因果结构.关联分析的一个典型例子是购物篮分析.通过发现顾客放入购物篮中不同商品之 ...

  6. 通过调用API在JavaWeb项目中实现证件识别

    本文详细介绍自己如何在JavaWeb项目中通过调用API实现证件识别. 一,Face++使用简介 二,两种方式(图片URL与本地上传)实现证件识别 一,Face++使用简介 Face++旷视人工智能开 ...

  7. Javaweb项目中出现java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone.异常

    javaweb项目中java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represent ...

  8. JavaWeb项目中获取对Oracle操作时抛出的异常错误码

    最近在项目中碰到了这么一个需求,一个JavaWeb项目,数据库用的是Oracle.业务上有一个对一张表的操作功能,当时设置了两个字段联合的唯一约束.由于前断没有对重复字段的校验,需要在插入时如果碰到唯 ...

  9. javaWeb项目中的路径格式 请求url地址 客户端路径 服务端路径 url-pattern 路径 获取资源路径 地址 url

    javaweb项目中有很多场景的路径客户端的POST/GET请求,服务器的请求转发,资源获取需要设置路径等这些路径表达的含义都有不同,所以想要更好的书写规范有用的路径代码 需要对路径有一个清晰地认知 ...

随机推荐

  1. PHP数组 转 对象/对象 转 数组

    /** * 数组 转 对象 * * @param array $arr 数组 * @return object */ function array_to_object($arr) { if (gett ...

  2. Oracle中table数据数据类型

    function F_ReturnDescription(varID in varchar2) return varchar2 is numDataCount ); mytable ly_family ...

  3. SQLite 如何取出特定部分数据

    如果我要取11-20的Students表的数据,则为: Select * From Students  Limit 9 Offset 10; 表示从Students  表获取数据,跳过10行,取9行 ...

  4. AtomicReference 原子引用

    AtomicReference和AtomicInteger非常类似,不同之处就在于AtomicInteger是对整数的封装,底层采用的是compareAndSwapInt实现CAS,比较的是数值是否相 ...

  5. 内网最小化安装CentOS后,想安装ISO文件中的包怎么办呢?

    昨日公司测试人员需要升级公司服务器Python,发现公司服务器上缺失了各种各样的包.比如open-ssl,python-deve等 1.查看你的Centos版本 lsb_release -a 2.上传 ...

  6. 小程序OSS图片上传

    图片上传加水印问题,代码如下! chooseImage: function (e) { var that = this; wx.chooseImage({ sizeType: ['original', ...

  7. ssh登录等待时间超时问题的解决

    最近使用ssh登录服务器时,发现许多服务器会报告等待时间超时的错误,通过网上查找发现是由于ssh中的配置中开启了DNS反查的功能,导致在反查过程中消耗了很长的时间,现将解决方法总结如下: 使用root ...

  8. 前端jQuery实现瀑布流

    瀑布流是我们经常会见到的东西,一直刷新一直有,其实它实现起来是很简单的.具体代码如下 1.css代码 <style> *{ margin:; padding:; } .container{ ...

  9. html5 video获取当前时间和视频总时间长度

    html: <video id="video-active" class="video-active" width="640" hei ...

  10. mysql 几种搜索引擎的比较

    mysql中常见的数据库引擎之间的比较  转载自 深入浅出mysql数据库 MySQL5.5以后默认使用InnoDB存储引擎,其中InnoDB和BDB提供事务安全表,其它存储引擎都是非事务安全表. 若 ...