<?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. H5多列布局

    多列布局 基本概念 1.多列布局类似报纸或杂志中的排版方式,上要用以控制大篇幅文本. 2.跨列属性可以控制横跨列的数量 /*列数*/ -webkit-column-count: 3; /*分割线*/ ...

  2. Spring配置cache(concurrentHashMap,guava cache、redis实现)附源码

    在应用程序中,数据一般是存在数据库中(磁盘介质),对于某些被频繁访问的数据,如果每次都访问数据库,不仅涉及到网络io,还受到数据库查询的影响:而目前通常会将频繁使用,并且不经常改变的数据放入缓存中,从 ...

  3. 神奇的 SQL 之 ICP → 索引条件下推

    开心一刻 楼主:来,我们先排练一遍 小伙伴们:好 嘿.哈.嚯 楼主:非常好,就是这个节奏,我们开始吧 楼主:啊.啊.啊,疼 ! 你们是不是故意的 ? 回表与覆盖索引 正式讲 ICP 之前了,我们先将相 ...

  4. python 深浅拷贝 元组 字典 集合操作

    深浅拷贝 :值拷贝 :ls = [,,] res = ls 则print(res)就是[,,] 浅拷贝 :ls.copy() 深拷贝:ls3 = deepcopy(ls) # 新开辟列表空间,ls列表 ...

  5. ubunto 免输入密码 登录 putty ssh-keygen

    交互式密码不安全,现在改用 ssh 证书方式,不用输入密码使用公钥证书登录. 方法1, 此方法,仅试用于,仅使用win putty 来连接方式使用,如果双方都是 linux 如 rsync 同步等时, ...

  6. vue中计算属性中的set和get

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <body& ...

  7. js 为数组编写该方法;indexOf

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  8. 在eclipse里面给maven项目打包

    eclipse中的“maven install”是用maven打包工程的意思. mvn install 是将用户打包好的jar包安装到本地仓库中,一般没有设置过的话默认在用户目录下的 .m2\下面. ...

  9. Javascript的document对象

    对象属性 document.title                 //设置文档标题等价于HTML的<title>标签 document.bgColor               / ...

  10. hdu2544SPFA板题

    SPFA顾名思义就是更快的最短路算法,是Bellman ford算法的优化,SPFA的平均复杂度大约是O(K*|E|),在一般情况下K大约是小于等于2的数,但是总有人对你心怀不轨,构造一组SPFA最坏 ...