Elasticsearch+spring cloud201912301423
<?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> <groupId>com.elasticsearch</groupId>
<artifactId>springboot-elasticsearch</artifactId>
<version>1.0-SNAPSHOT</version> <name>springboot-elasticsearch</name>
<description></description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
</parent> <dependencies> <dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency> <dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.5.0</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>7.5.0</version>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>2.0.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.7.RELEASE</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.elasticsearch.plugin/transport-netty4-client -->
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
<version>7.5.0</version>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build> </project>
pom.xml
package org.jimmy.autosearch.config; import org.elasticsearch.action.bulk.BackoffPolicy;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException; @Configuration
@SuppressWarnings({ "resource", "deprecation" })
public class ElasticSearchConfig { private static final Logger logger = LoggerFactory.getLogger(ElasticSearchConfig.class); private String host = "127.0.0.1";//elasticsearch的地址 private Integer port = 9300;//elasticsearch的端口 private String clusterName = "elasticsearch";//集群 private TransportClient transportClient; @Bean
public TransportClient transportClient(){
Settings settings = Settings.builder()
.put("cluster.name", clusterName)
.build();
try {
transportClient = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName(host), port));
} catch (UnknownHostException e) {
logger.error("创建elasticsearch客户端失败");
e.printStackTrace();
}
logger.info("创建elasticsearch客户端成功");
return transportClient;
} @Bean
public BulkProcessor bulkProcessor() throws UnknownHostException {
Settings settings = Settings.builder()
.put("cluster.name", clusterName)
.build();
TransportClient transportClient = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName(host), port));
return BulkProcessor.builder(transportClient, new BulkProcessor.Listener() {
@Override
public void beforeBulk(long l, BulkRequest bulkRequest) { } @Override
public void afterBulk(long l, BulkRequest bulkRequest, BulkResponse bulkResponse) { } @Override
public void afterBulk(long l, BulkRequest bulkRequest, Throwable throwable) {
logger.error("{} data bulk failed,reason :{}", bulkRequest.numberOfActions(), throwable);
} }).setBulkActions(1000)//分批,每10000条请求当成一批请求。默认值为1000
.setBulkSize(new ByteSizeValue(5, ByteSizeUnit.MB))//每次5MB,刷新一次bulk。默认为5m
.setFlushInterval(TimeValue.timeValueSeconds(5))//每5秒一定执行,不管已经队列积累了多少。默认不设置这个值
.setConcurrentRequests(1)//设置并发请求数,如果是0,那表示只有一个请求就可以被执行,如果为1,则可以积累并被执行。默认为1.
.setBackoffPolicy(BackoffPolicy.exponentialBackoff(TimeValue.timeValueMillis(100), 3))//这里有个backoff策略,最初等待100ms,然后按照指数增长并重试3次。每当一个或者多个bulk请求失败,并出现EsRejectedExecutionException异常时.就会尝试重试。这个异常表示用于处理请求的可用计算资源太少。如果要禁用这个backoff策略,需要用backoff.nobackoff()。
.build();
} @PostConstruct
void init() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
} }
ElasticSearchConfig.java
package org.jimmy.autosearch.service; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jimmy.autosearch.pojo.EsEntity; /**
*
*/
public interface QueryService<T> { List<Map<String, Object>> queryListFromES(EsEntity es, int storeId, String storeName, String startDate, String endDate); ArrayList<T> findByParams(EsEntity es, HashMap<String, String> params); }
QueryService.java
package org.jimmy.autosearch.service.impl; import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.PipelineAggregatorBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.Sum;
import org.jimmy.autosearch.pojo.Article;
import org.jimmy.autosearch.pojo.EsEntity;
import org.jimmy.autosearch.service.QueryService;
import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import javax.annotation.Resource;
import java.util.*;
import java.util.Map.Entry; /**
* Created by baishuai on 2018/12/18
*/
@Service
@SuppressWarnings("deprecation")
public class ArticleQueryServiceImpl implements QueryService<Article> { @Resource
TransportClient transportClient;//注入es操作对象 @Override
public ArrayList<Article> findByParams(EsEntity es, HashMap<String, String> params) {
ArrayList<Article> articleList = new ArrayList<Article>();
SearchRequestBuilder searchRequest = transportClient.prepareSearch(es.getIndex()).setTypes(es.getType());
if(params != null){
Set<Entry<String, String>> paramsEntry = params.entrySet();
paramsEntry.forEach(param -> {
searchRequest.setQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery(param.getKey() + ".keyword", param.getValue())));
});
}
SearchResponse searchResponse = searchRequest.execute().actionGet();
SearchHits hits = searchResponse.getHits();
hits.forEach(h -> {
if(h != null && h.getSourceAsString() != null
&& h.getSourceAsString().trim().length() > 0){
String content = h.getSourceAsString();
JSONObject jsonObject = JSONObject.parseObject(content);
Article article = JSON.toJavaObject(jsonObject, Article.class);
articleList.add(article);
}
});
return articleList;
} public HashMap<String, Object> paging(ArrayList<Article> articleList, Integer page, Integer size){
HashMap<String, Object> map = new HashMap<String, Object>();
if(page == null){
page = 0;
}
if(size == null){
size = 10;
}
int count = articleList.size();
int maxPageSize = 0;
if(count > 0){
maxPageSize = (count - 1) / size + 1;
}
ArrayList<Article> list = new ArrayList<Article>();
int beginIndex = page * size;
int endIndex = (page + 1) * size > count ? count : (page + 1) * size;
for(int i = beginIndex; i < endIndex; i++){
list.add(articleList.get(i));
}
map.put("list", list);
map.put("page", page);
map.put("size", size);
map.put("maxPageSize", maxPageSize);
return map;
} @Override
public List<Map<String, Object>> queryListFromES(EsEntity es, int storeId, String storeName, String startDate, String endDate) { List<Map<String, Object>> list = new ArrayList<>(); Map<String,Object> map = Collections.emptyMap(); Script script = new Script(ScriptType.INLINE, "painless","params._value0 > 0",map); //提前定义好查询销量是否大于1000的脚本,类似SQL里面的having long beginTime = System.currentTimeMillis(); SearchResponse sr = transportClient.prepareSearch(es.getIndex()).setTypes(es.getType()) //要查询的表
.setQuery(QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("store_id", storeId)) //挨个设置查询条件,没有就不加,如果是字符串类型的,要加keyword后缀
.must(QueryBuilders.termQuery("store_name.keyword", storeName))
.must(QueryBuilders.rangeQuery("pay_date.keyword").gte(startDate).lte(endDate))
).addAggregation(
AggregationBuilders.terms("by_product_code").field("product_code.keyword").size(2000) //按货号分组,最多查500个货号.SKU直接改字段名字就可以
.subAggregation(AggregationBuilders.sum("quantity").field("quantity")) //分组计算销量汇总
.subAggregation(AggregationBuilders.sum("amount").field("amount")) //分组计算实付款汇总,需要加其他汇总的在这里依次加
.subAggregation(PipelineAggregatorBuilders.bucketSelector("sales_bucket_filter",script,"quantity"))//查询是否大于指定值
.order(BucketOrder.aggregation("amount", false))) //分组排序 .execute().actionGet(); Terms terms = sr.getAggregations().get("by_product_code"); //查询遍历第一个根据货号分组的aggregation System.out.println(terms.getBuckets().size());
for (Terms.Bucket entry : terms.getBuckets()) {
Map<String,Object> objectMap = new HashMap<>();
System.out.println("------------------");
System.out.println("【 " + entry.getKey() + " 】订单数 : " + entry.getDocCount() ); Sum sum0 = entry.getAggregations().get("quantity"); //取得销量的汇总
Sum sum1 = entry.getAggregations().get("amount"); //取得销量的汇总 objectMap.put("product_code", entry.getKey());
objectMap.put("quantity",sum0.getValue());
objectMap.put("amount",sum1.getValue());
list.add(objectMap);
} long endTime = System.currentTimeMillis();
System.out.println("查询耗时" + ( endTime - beginTime ) + "毫秒"); return list;
} }
ArticleQueryServiceImpl.java
package org.jimmy.autosearch.util; import java.util.List;
import java.util.Map; /**
*
*/
public class EmptyUtils { public static boolean isEmpty(Object s) {
if (s == null) {
return true;
}
if ((s instanceof String) && (((String)s).trim().length() == 0)) {
return true;
}
if (s instanceof Map) {
return ((Map<?, ?>)s).isEmpty();
}
if (s instanceof List) {
return ((List<?>)s).isEmpty();
}
if (s instanceof Object[]) {
return (((Object[])s).length == 0);
}
return false;
} }
EmptyUtils.java
package org.jimmy.autosearch.controller; import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap; import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse; import org.jimmy.autosearch.pojo.Article;
import org.jimmy.autosearch.pojo.EsEntity;
import org.jimmy.autosearch.service.impl.ArticleQueryServiceImpl;
import org.jimmy.autosearch.service.impl.ElasticSearchServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; @Controller
@RequestMapping("/article")
@SuppressWarnings("unchecked")
public class ArticleController { @Resource
private ArticleQueryServiceImpl articleQueryService;
@Resource
private ElasticSearchServiceImpl elasticSearchService; @RequestMapping(value = "/index")
public String index(){
return "article";
} @RequestMapping(value = "/add", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
public String addArticle(@RequestBody Article article){
/*articleService.save(article);
JSONObject jsonObject = new JSONObject();
jsonObject.put("status", "success");
String result = jsonObject.toJSONString();
return result;*/
return null;
} @ResponseBody
@RequestMapping(value = "/findByKey/{key}/{page}/{size}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
public void findByKey(@PathVariable String key, @PathVariable int page, @PathVariable int size, HttpServletResponse response){
try{
EsEntity es = new EsEntity();
es.setIndex("jimmy_article");
es.setType("article");
HashMap<String, String> params = null;
if(key != null && key.trim().length() > 0){
params = new HashMap<String, String>();
params.put("message", key);
}
ArrayList<Article> articleList = articleQueryService.findByParams(es, params);
HashMap<String, Object> resultMap = articleQueryService.paging(articleList, page, size);
ArrayList<Article> list = (ArrayList<Article>) resultMap.get("list");
Integer maxPageSize = (Integer) resultMap.get("maxPageSize");
JSONArray jsonArray = new JSONArray();
list.forEach(a -> jsonArray.add(a));
JSONObject jsonObject = new JSONObject();
jsonObject.put("articleList", jsonArray);
jsonObject.put("page", page);
jsonObject.put("size", size);
jsonObject.put("maxPageSize", maxPageSize);
response.setContentType("text/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.println(jsonObject);
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
}
} }
ArticleController.java
效果图:
修改后的ArticleQueryServiceImpl,201912301426
package org.jimmy.autosearch.service.impl; import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.PipelineAggregatorBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.Sum;
import org.jimmy.autosearch.pojo.Article;
import org.jimmy.autosearch.pojo.EsEntity;
import org.jimmy.autosearch.service.QueryService;
import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import javax.annotation.Resource;
import java.util.*;
import java.util.Map.Entry; /**
* Created by baishuai on 2018/12/18
*/
@Service
@SuppressWarnings("deprecation")
public class ArticleQueryServiceImpl implements QueryService<Article> { @Resource
TransportClient transportClient;//注入es操作对象 @Override
public ArrayList<Article> findByParams(EsEntity es, HashMap<String, String> params) {
ArrayList<Article> articleList = new ArrayList<Article>();
SearchRequestBuilder searchRequest = transportClient.prepareSearch(es.getIndex()).setTypes(es.getType()).setSize(10000);
if(params != null){
Set<Entry<String, String>> paramsEntry = params.entrySet();
paramsEntry.forEach(param -> {
searchRequest.setQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery(param.getKey() + ".keyword", param.getValue())));
});
}
SearchResponse searchResponse = searchRequest.execute().actionGet();
SearchHits hits = searchResponse.getHits();
hits.forEach(h -> {
if(h != null && h.getSourceAsString() != null
&& h.getSourceAsString().trim().length() > 0){
String content = h.getSourceAsString();
JSONObject jsonObject = JSONObject.parseObject(content);
Article article = JSON.toJavaObject(jsonObject, Article.class);
articleList.add(article);
}
});
return articleList;
} public HashMap<String, Object> paging(ArrayList<Article> articleList, Integer page, Integer size){
HashMap<String, Object> map = new HashMap<String, Object>();
if(page == null){
page = 0;
}
if(size == null){
size = 10;
}
int count = articleList.size();
int maxPageSize = 0;
if(count > 0){
maxPageSize = (count - 1) / size + 1;
}
ArrayList<Article> list = new ArrayList<Article>();
int beginIndex = page * size;
int endIndex = (page + 1) * size > count ? count : (page + 1) * size;
for(int i = beginIndex; i < endIndex; i++){
list.add(articleList.get(i));
}
map.put("list", list);
map.put("page", page);
map.put("size", size);
map.put("maxPageSize", maxPageSize);
return map;
} @Override
public List<Map<String, Object>> queryListFromES(EsEntity es, int storeId, String storeName, String startDate, String endDate) { List<Map<String, Object>> list = new ArrayList<>(); Map<String,Object> map = Collections.emptyMap(); Script script = new Script(ScriptType.INLINE, "painless","params._value0 > 0",map); //提前定义好查询销量是否大于1000的脚本,类似SQL里面的having long beginTime = System.currentTimeMillis(); SearchResponse sr = transportClient.prepareSearch(es.getIndex()).setTypes(es.getType()) //要查询的表
.setQuery(QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("store_id", storeId)) //挨个设置查询条件,没有就不加,如果是字符串类型的,要加keyword后缀
.must(QueryBuilders.termQuery("store_name.keyword", storeName))
.must(QueryBuilders.rangeQuery("pay_date.keyword").gte(startDate).lte(endDate))
).addAggregation(
AggregationBuilders.terms("by_product_code").field("product_code.keyword").size(2000) //按货号分组,最多查500个货号.SKU直接改字段名字就可以
.subAggregation(AggregationBuilders.sum("quantity").field("quantity")) //分组计算销量汇总
.subAggregation(AggregationBuilders.sum("amount").field("amount")) //分组计算实付款汇总,需要加其他汇总的在这里依次加
.subAggregation(PipelineAggregatorBuilders.bucketSelector("sales_bucket_filter",script,"quantity"))//查询是否大于指定值
.order(BucketOrder.aggregation("amount", false))) //分组排序 .execute().actionGet(); Terms terms = sr.getAggregations().get("by_product_code"); //查询遍历第一个根据货号分组的aggregation System.out.println(terms.getBuckets().size());
for (Terms.Bucket entry : terms.getBuckets()) {
Map<String,Object> objectMap = new HashMap<>();
System.out.println("------------------");
System.out.println("【 " + entry.getKey() + " 】订单数 : " + entry.getDocCount() ); Sum sum0 = entry.getAggregations().get("quantity"); //取得销量的汇总
Sum sum1 = entry.getAggregations().get("amount"); //取得销量的汇总 objectMap.put("product_code", entry.getKey());
objectMap.put("quantity",sum0.getValue());
objectMap.put("amount",sum1.getValue());
list.add(objectMap);
} long endTime = System.currentTimeMillis();
System.out.println("查询耗时" + ( endTime - beginTime ) + "毫秒"); return list;
} }
修改后的ArticleController,201912301427
package org.jimmy.autosearch.controller; import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.jimmy.autosearch.pojo.Article;
import org.jimmy.autosearch.pojo.EsEntity;
import org.jimmy.autosearch.service.impl.ArticleQueryServiceImpl;
import org.jimmy.autosearch.service.impl.ElasticSearchServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; @Controller
@RequestMapping("/article")
@SuppressWarnings("unchecked")
public class ArticleController { @Resource
private ArticleQueryServiceImpl articleQueryService;
@Resource
private ElasticSearchServiceImpl elasticSearchService;
private static final String INDEX = "jimmy_article";
private static final String TYPE = "article";
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @RequestMapping(value = "/index/{key}/{page}/{size}")
public String index(@PathVariable String key, @PathVariable String page, @PathVariable String size, HttpServletRequest request){
request.setAttribute("key", key);
request.setAttribute("page", page);
request.setAttribute("size", size);
return "article";
} @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
public void deleteArticle(@PathVariable String id, HttpServletResponse response){
JSONObject jsonObject = new JSONObject();
String status = "failed";
try{
elasticSearchService.deleteById(INDEX, TYPE, id);
status = "success";
}catch(Exception e){
e.printStackTrace();
}finally{
jsonObject.put("status", status);
}
try{
response.setContentType("text/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.println(jsonObject);
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
}
} @RequestMapping(value = "/addOrUpdate/{jsonStr}", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
public void addOrUpdateArticle(@PathVariable String jsonStr, HttpServletResponse response){
JSONObject jsonObject = new JSONObject();
String status = "failed";
try{
JSONObject jsonData = JSONObject.parseObject(jsonStr);
String postDate = sdf.format(new Date());
jsonData.put("postDate", postDate);
String id = jsonData.getString("id");
if(id == null || id.trim().length() == 0){
UUID uuid = UUID.randomUUID();
id = uuid.toString();
jsonData.put("id", id);
jsonStr = jsonData.toJSONString();
elasticSearchService.insertById(INDEX, TYPE, id, jsonStr);
}else{
jsonStr = jsonData.toJSONString();
elasticSearchService.updateById(INDEX, TYPE, id, jsonStr);
}
status = "success";
}catch(Exception e){
e.printStackTrace();
}finally{
jsonObject.put("status", status);
}
try{
response.setContentType("text/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.println(jsonObject);
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
}
} @RequestMapping(value = "/edit/{type}/{jsonStr}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
public String add(@PathVariable String type, @PathVariable String jsonStr, HttpServletRequest request){
if(type.equals("0")){
//新增
}else if(type.equals("1")){
//修改
if(jsonStr != null && jsonStr.trim().length() > 0){
JSONObject jsonData = JSONObject.parseObject(jsonStr);
String id = jsonData.getString("id");
request.setAttribute("id", id);
String user = jsonData.getString("user");
request.setAttribute("user", user);
String message = jsonData.getString("message");
request.setAttribute("message", message);
}
}
return "articleEdit";
} @ResponseBody
@RequestMapping(value = "/findByKey/{key}/{page}/{size}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
public void findByKey(@PathVariable String key, @PathVariable int page, @PathVariable int size, HttpServletResponse response){
try{
EsEntity es = new EsEntity();
es.setIndex("jimmy_article");
es.setType("article");
HashMap<String, String> params = null;
if(key != null && key.trim().length() > 0){
params = new HashMap<String, String>();
params.put("message", key);
}
ArrayList<Article> articleList = articleQueryService.findByParams(es, params);
HashMap<String, Object> resultMap = articleQueryService.paging(articleList, page, size);
ArrayList<Article> list = (ArrayList<Article>) resultMap.get("list");
Integer maxPageSize = (Integer) resultMap.get("maxPageSize");
JSONArray jsonArray = new JSONArray();
list.forEach(a -> jsonArray.add(a));
JSONObject jsonObject = new JSONObject();
jsonObject.put("articleList", jsonArray);
jsonObject.put("page", page);
jsonObject.put("size", size);
jsonObject.put("maxPageSize", maxPageSize);
response.setContentType("text/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.println(jsonObject);
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
}
} }
页面,201912301427
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="http://127.0.0.1:10001/js/jquery-1.12.4.js"></script>
<style type="text/css"> #articleListTable {
border: 1px solid black;
border-collapse: collapse;
} #articleListTable tr td {
border: 1px solid black;
} #pageSetting {
width: 100%;
text-align: center;
} #pageSetting tr td {
border: 0;
} </style>
</head>
<body> <div id="articleList">
<table id="articleListTable" >
<tr>
<td>
id
</td>
<td>
user
</td>
<td>
message
</td>
<td>
postDate
</td>
<td>
operate
</td>
</tr>
</table>
</div> <div id="articleTitleDiv" style="display: none;">
<table id="articleTitle">
<tr>
<td>
id
</td>
<td>
user
</td>
<td>
message
</td>
<td>
postDate
</td>
<td>
operate
</td>
</tr>
</table>
</div> <script type="text/javascript"> var key = '${requestScope.key}' == '' ? '%20' : '${requestScope.key}';
var pageIndex = '${requestScope.page}';
var pageSize = '${requestScope.size}';
var maxPageSize = 0;
var searchObj = {}; $(function(){ $.ajax({
url: '/article/findByKey/' + key + '/' + pageIndex + '/' + pageSize,
data: searchObj,
type: 'get',
dataType: 'json',
success: function (result) {
if(result){
var articleList = result.articleList;
if(articleList){
for(var i = 0; i < articleList.length; i++){
var article = articleList[i];
var html = '<tr>'
+ '<td>'
+ article.id
+ '</td>'
+ '<td>'
+ article.user
+ '</td>'
+ '<td>'
+ article.message
+ '</td>'
+ '<td>'
+ article.postDate
+ '</td>'
+ '<td>'
+ '<a href="javascript: void(0);" class="add">新增</a> '
+ '<a href="javascript: void(0);" class="update">修改</a> '
+ '<a href="javascript: void(0);" class="delete">删除</a> '
+ '</td>'
+ '</tr>';
$("#articleListTable").append(html);
}
var pageParams = {};
pageParams.pageIndex = result.page;
pageParams.maxPageSize = result.maxPageSize;
maxPageSize = pageParams.maxPageSize;
loadPageSetting(pageParams);
addClick();
updateClick();
deleteClick();
firstPageClick();
previousPageClick();
nextPageClick();
lastPageClick();
}
}
}
}); }); function lastPageClick(){
$("#lastPage").on("click", function(){
var index = 0;
if(maxPageSize > 0){
index = maxPageSize - 1;
}
window.location = '/article/index/' + key + '/' + index + '/' + pageSize + '/';
});
} function nextPageClick(){
$("#nextPage").on("click", function(){
var currentPage = $("#currentPage").text();
currentPage = parseInt(currentPage);
currentPage++;
if(currentPage > maxPageSize){
currentPage = maxPageSize;
}
var index = currentPage - 1;
window.location = '/article/index/' + key + '/' + index + '/' + pageSize + '/';
});
} function previousPageClick(){
$("#previousPage").on("click", function(){
var currentPage = $("#currentPage").text();
currentPage = parseInt(currentPage);
currentPage--;
var index = 0;
if(currentPage < 0){
currentPage = 0;
index = currentPage;
}else{
index = currentPage - 1;
}
window.location = '/article/index/' + key + '/' + index + '/' + pageSize + '/';
});
} function firstPageClick(){
$("#firstPage").on("click", function(){
window.location = '/article/index/' + key + '/' + 0 + '/' + pageSize + '/';
});
} function deleteClick(){
$(".delete").on("click", function(){
var flag = confirm("确认删除吗?");
if(flag){
var id = $(this).parent().parent().children("td:eq(0)").text();
$.ajax({
url: '/article/delete/' + id,
data: searchObj,
type: 'post',
dataType: 'json',
success: function (result) {
if(result){
var status = result.status;
if(status == 'success'){
alert("删除成功!");
location.reload();
}else{
alert("删除失败!");
}
}
}
});
}
});
} function updateClick(){
$(".update").on("click", function(){
var type = "1";
var id = $(this).parent().parent().children("td:eq(0)").text();
var user = $(this).parent().parent().children("td:eq(1)").text();
var message = $(this).parent().parent().children("td:eq(2)").text();
var jsonObject = {};
jsonObject.id = id;
jsonObject.user = user;
jsonObject.message = message;
var jsonStr = JSON.stringify(jsonObject);
window.location = '/article/edit/' + type + '/' + jsonStr;
});
} function addClick(){
$(".add").on("click", function(){
var type = "0";
var jsonObject = {};
var jsonStr = JSON.stringify(jsonObject);
window.location = '/article/edit/' + type + '/' + jsonStr;
});
} function loadPageSetting(pageParams){
var html = '<tr>'
+ '<td colspan="5">'
+ '<table id="pageSetting">'
+ '<tr>'
+ '<td>'
+ '<a href="javascript: void(0);" id="firstPage">首页</a>'
+ ' '
+ '<a href="javascript: void(0);" id="previousPage">上一页</a>'
+ ' '
+ '<a href="javascript: void(0);" id="nextPage">下一页</a>'
+ ' '
+ '<a href="javascript: void(0);" id="lastPage">尾页</a>'
+ ' '
+ '当前第<span id="currentPage">' + (pageParams.pageIndex + 1) + '</span>页'
+ ' '
+ '共' + pageParams.maxPageSize + '页'
+ '</td>'
+ '</tr>'
+ '</table>'
+ '</td>'
+ '</tr>';
$("#articleListTable").append(html);
} </script> </body>
</html>
效果图:
参考:
https://github.com/whiney/springboot-elasticsearch
里面具体逻辑实现我进行了修改,毕竟要符合实际.
Elasticsearch+spring cloud201912301423的更多相关文章
- elasticsearch spring 集成
elasticsearch spring 集成 项目清单 elasticsearch服务下载包括其中插件和分词 http://download.csdn.net/detail/u0142011 ...
- elasticSearch+spring 整合 maven依赖详解
摘自:http://www.mayou18.com/detail/nTxPQSyu.html [Elasticsearch基础]elasticSearch+spring 整合 maven依赖详解 Ma ...
- Spring Boot + Elasticsearch
spring data elasticsearch elasticsearch 2.0.0.RELEASE 2.2.0 1.4.0.M1 1.7.3 1.3.0.RELEASE 1.5.2 1.2.0 ...
- Spring Boot 整合 Elasticsearch,实现 function score query 权重分查询
摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 预见未来最好的方式就是亲手创造未来 – <史蒂夫·乔布斯传> 』 运行环境: ...
- elasticsearch 的安装配置与spring boot的整合应用
linux上的elasticsearch安装 一.下载elasticsearch 直接进入elasticsearch的官网,下载最新的安装包:https://www.elastic.co/downlo ...
- Spring Boot 整合 elasticsearch
一.简介 我们的应用经常需要添加检索功能,开源的 ElasticSearch 是目前全文搜索引擎的 首选.他可以快速的存储.搜索和分析海量数据.Spring Boot通过整合Spring Data E ...
- Spring Boot + Elasticsearch 实现索引批量写入
在使用Eleasticsearch进行索引维护的过程中,如果你的应用场景需要频繁的大批量的索引写入,再使用上篇中提到的维护方法的话显然效率是低下的,此时推荐使用bulkIndex来提升效率.批写入数据 ...
- 从零搭建Spring Boot脚手架(7):Elasticsearch应该独立服务
1. Spring Data Elasticsearch Spring Data Elasticsearch是Spring Data项目的子项目,提供了Elasticsearch与Spring的集成. ...
- Spring Boot + Elasticsearch 使用示例
本文分别使用 Elasticsearch Repository 和 ElasticsearchTemplate 实现 Elasticsearch 的简单的增删改查 一.Elastic Stack El ...
随机推荐
- Nginx的工作原理
Nginx 工作原理 Nginx由内核和模块组成. Nginx本身做的工作实际很少,当它接到一个HTTP请求时,它仅仅是通过查找配置文件将此次请求映射到一个location block,而此locat ...
- Ubuntu16.04下安装nvidia-docker2
若docker-ce.nvidia.CUDA等都安装完成之后,开启docker服务时,能够正常运行,并有预测结果,那表示服务开启没问题:若都安装成功之后,用docker命令开启服务时,一直报错,可能表 ...
- Apache Druid 的集群设计与工作流程
导读:本文将描述 Apache Druid 的基本集群架构,说明架构中各进程的作用.并从数据写入和数据查询两个角度来说明 Druid 架构的工作流程. 关注公众号 MageByte,设置星标点「在看」 ...
- Linux 文件系统及 ext2 文件系统
linux 支持的文件系统类型 Ext2: 有点像 UNIX 文件系统.有 blocks,inodes,directories 的概念. Ext3: Ext2 的加强版,添加了日志 ...
- 原生的ajax,get post请求需要注意的地方
1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.o ...
- 从零搭建Spring Cloud Gateway网关(二)—— 打印请求响应日志
作为网关,日志记录是必不可少的功能,可以在网关出增加requestId来查询整个请求链的调用执行情况等等. 打印请求日志 打印请求日志最重要的就是打印请求参数这些东西,不过RequestBody通常情 ...
- .Net Core 实现图片验证码
记录自己的学习,参考了网上各位大佬的技术,往往在登录的时候需要使用到验证码来进行简单的一个校验,这边使用在.net core上进行生成图片二维码 思路很简单=> 生成一个随机数->保存到服 ...
- 「每天五分钟,玩转 JVM」:对象访问定位
前言 在「对象内存布局」一节中,我们了解到对象头中包含了一个叫做类型指针的东西,即对象指向它的类元数据的指针,虚拟机通过这个指针来确定这个对象是哪个类的实例.但是,并不是所有的虚拟机都是这么去做的.不 ...
- Java锁的深度化--重入锁、读写锁、乐观锁、悲观锁
Java锁 锁一般来说用作资源控制,限制资源访问,防止在并发环境下造成数据错误 锁作为并发共享数据,保证一致性的工具,在JAVA平台有多种实现(如 synchronized(重量级) 和 Reentr ...
- 通达OA rce复现
通达OA下载:链接:https://pan.baidu.com/s/1c0P-M-IyY5VxfH5d0qKHsQ 提取码:l0pc 漏洞原因:未授权文件上传 + 文件包含(利用nginx日志也可以g ...