<?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>&nbsp;'
+ '<a href="javascript: void(0);" class="update">修改</a>&nbsp;'
+ '<a href="javascript: void(0);" class="delete">删除</a>&nbsp;'
+ '</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>'
+ '&nbsp;'
+ '<a href="javascript: void(0);" id="previousPage">上一页</a>'
+ '&nbsp;'
+ '<a href="javascript: void(0);" id="nextPage">下一页</a>'
+ '&nbsp;'
+ '<a href="javascript: void(0);" id="lastPage">尾页</a>'
+ '&nbsp;'
+ '当前第<span id="currentPage">' + (pageParams.pageIndex + 1) + '</span>页'
+ '&nbsp;'
+ '共' + pageParams.maxPageSize + '页'
+ '</td>'
+ '</tr>'
+ '</table>'
+ '</td>'
+ '</tr>';
$("#articleListTable").append(html);
} </script> </body>
</html>

效果图:

参考:

https://github.com/whiney/springboot-elasticsearch

里面具体逻辑实现我进行了修改,毕竟要符合实际.

Elasticsearch+spring cloud201912301423的更多相关文章

  1. elasticsearch spring 集成

    elasticsearch spring 集成 项目清单   elasticsearch服务下载包括其中插件和分词   http://download.csdn.net/detail/u0142011 ...

  2. elasticSearch+spring 整合 maven依赖详解

    摘自:http://www.mayou18.com/detail/nTxPQSyu.html [Elasticsearch基础]elasticSearch+spring 整合 maven依赖详解 Ma ...

  3. 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 ...

  4. Spring Boot 整合 Elasticsearch,实现 function score query 权重分查询

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 预见未来最好的方式就是亲手创造未来 – <史蒂夫·乔布斯传> 』 运行环境: ...

  5. elasticsearch 的安装配置与spring boot的整合应用

    linux上的elasticsearch安装 一.下载elasticsearch 直接进入elasticsearch的官网,下载最新的安装包:https://www.elastic.co/downlo ...

  6. Spring Boot 整合 elasticsearch

    一.简介 我们的应用经常需要添加检索功能,开源的 ElasticSearch 是目前全文搜索引擎的 首选.他可以快速的存储.搜索和分析海量数据.Spring Boot通过整合Spring Data E ...

  7. Spring Boot + Elasticsearch 实现索引批量写入

    在使用Eleasticsearch进行索引维护的过程中,如果你的应用场景需要频繁的大批量的索引写入,再使用上篇中提到的维护方法的话显然效率是低下的,此时推荐使用bulkIndex来提升效率.批写入数据 ...

  8. 从零搭建Spring Boot脚手架(7):Elasticsearch应该独立服务

    1. Spring Data Elasticsearch Spring Data Elasticsearch是Spring Data项目的子项目,提供了Elasticsearch与Spring的集成. ...

  9. Spring Boot + Elasticsearch 使用示例

    本文分别使用 Elasticsearch Repository 和 ElasticsearchTemplate 实现 Elasticsearch 的简单的增删改查 一.Elastic Stack El ...

随机推荐

  1. 本地目录配置多个远程Git仓库

    目录 情景一:不同的库分别 pull/push 1. 使用git命令配置 2. 修改.git/config 文件 3. 操作 情景二:不同的库一次push 1. 使用git命令配置 2. 修改.git ...

  2. NTP网络时钟服务器品牌

    NTP网络时钟服务器品牌 在科技的不断进步和发展下,时钟的种类和功能也在发生着变化,以满足人们的各种需求,时钟从原始的机械时钟发展成具有多钟功能的时钟.而时钟服务器主要是给时钟提供时间信息的,时钟服务 ...

  3. ReentrantLock 源码分析以及 AQS (一)

    前言 JDK1.5 之后发布了JUC(java.util.concurrent),用于解决多线程并发问题.AQS 是一个特别重要的同步框架,很多同步类都借助于 AQS 实现了对线程同步状态的管理. A ...

  4. 【小程序】---- input获得焦点时placeholder重影BUG

    问题小程序的input组件有个自身的bug,即当输入框获取焦点时placeholder内容会出现重影现象. 解决思路原理:将placeholder内容单独写在另外的标签里,控制其显示隐藏.操作:将代表 ...

  5. BERT实现QA中的问句语义相似度计算

    1. BERT 语义相似度 BERT的全称是Bidirectional Encoder Representation from Transformers,是Google2018年提出的预训练模型,即双 ...

  6. Python xlsxwriter模块

    1.简介: xlsxWriter支持多种excle功能:与excel完美兼容:写大文件,速度快且只占用很小的内存空间不支持读或者改现有的excel文件 2.安装: pip install xlsxwr ...

  7. Python 3.9 新特性:任意表达式可作为装饰器!

    一个月前(2月20日),一则新的 PEP 没有受到任何阻碍就被官方采纳了,这么快的速度,似乎并不多见. 然而,更为高效率的是,仅在半个月内,它的实现就被合入了代码仓.也就是说,我们最快有望在 3 天后 ...

  8. JavaScript初学者

    学习如逆水行舟,不进则退.要逆流而上,逆战! 学习JavaScript这门语言,作为一个初学者,最重要的就是扎实的基础. 只要有了扎实的功底,在后期的学习中才能来去自如的应对各种逻辑难题 下面我们就来 ...

  9. 推荐两款好用的JS格式化工具

    工具一: 直接在Chrome浏览器中,F12,打开Sources栏,找到JS文件,点击下面的花括号即可. 工具二: 使用notepad++ 格式化JS文件. 1.下载 jstool 插件(https: ...

  10. shell编程之字符串处理

    # .#号截取,删除左边字符,保留右边字符,*// 表示从左边开始删除第一个 // 号及左边的所有字符 echo ${var#*//} # . ## 号截取,删除左边字符,保留右边字符,##*/ 表示 ...