国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - spring 操作elasticsearch查詢使用方法

spring 操作elasticsearch查詢使用方法

2020-10-20 10:23GOODDEEP Java教程

本篇文章主要介紹了spring 操作elasticsearch使用方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

最近學習了一下elasticsearch使用,網上的資料又很少,真是一個頭兩個大。好歹最后終于了解了。留個筆記做日后查詢。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package com.gooddeep.dev.elasticsearch.commons.dao;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.highlight.HighlightBuilder;
import org.elasticsearch.search.highlight.HighlightBuilder.Field;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.DeleteQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.core.query.StringQuery;
import org.springframework.stereotype.Component;
 
import com.gooddeep.dev.core.helper.PropertyHelper;
import com.gooddeep.dev.core.helper.UuidHelper;
import com.gooddeep.dev.core.model.BasePage;
import com.gooddeep.dev.elasticsearch.commons.model.EsBaseBean;
import com.gooddeep.dev.elasticsearch.commons.service.EsBaseService;
 
@Component("esBaseDao")
public abstract class EsBaseDaoImpl<T> implements EsBaseDao<T> {
 
  private Logger logger = LoggerFactory.getLogger(EsBaseService.class);
 
  @Autowired
  private ElasticsearchTemplate elasticsearchTemplate;
 
  @Autowired
  private Client esClient;
 
   
  /**
   * 插入或等新,需要有id,id需要自己生成
   
   * @param tList
   * @return
   */
  public boolean insertOrUpdate(List<T> tList) {
    List<IndexQuery> queries = new ArrayList<IndexQuery>();
    for (T t : tList) {
      String id = ((EsBaseBean) t).getId();
      if (id == null) {
        id = UuidHelper.getRandomUUID();
        ((EsBaseBean) t).setId(id);
      }
      IndexQuery indexQuery = new IndexQueryBuilder().withId(id).withObject(t).build();
      queries.add(indexQuery);
    }
    elasticsearchTemplate.bulkIndex(queries);
    return true;
  }
 
  /**
   * 插入或更新
   
   * @param t
   * @return
   */
  public boolean insertOrUpdate(T t) {
 
    String id = ((EsBaseBean) t).getId();
    if (id == null) {
      id = UuidHelper.getRandomUUID();
      ((EsBaseBean) t).setId(id);
    }
    try {
      IndexQuery indexQuery = new IndexQueryBuilder().withId(id).withObject(t).build();
      elasticsearchTemplate.index(indexQuery);
      return true;
    } catch (Exception e) {
      logger.error("insert or update user info error.", e);
      return false;
    }
  }
 
  /**
   * 刪除
   
   * @param id
   * @return
   */
  public boolean deleteById(String id) {
    try {
      elasticsearchTemplate.delete(getEntityClass(), id);
      return true;
    } catch (Exception e) {
      logger.error("delete " + getEntityClass() + " by id " + id
          + " error.", e);
      return false;
    }
  }
   
  /**
   * 刪除ids
   * @param idList
   * @return
   */
  @Override
  public boolean deleteByIds(List<String> idList) {
    try {
       CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria());
       criteriaQuery.setIds(idList);
       elasticsearchTemplate.delete(criteriaQuery, getEntityClass());
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
 
 
  /**
   * 根據條件查詢
   * @param filedContentMap 不能為null
   * @return
   */
  public boolean deleteByQuery(Map<String,Object> filedContentMap) {
    try {
      DeleteQuery dq = new DeleteQuery();
       
      BoolQueryBuilder qb=QueryBuilders. boolQuery();
      if(filedContentMap!=null)
        for (String key : filedContentMap.keySet()) {//字段查詢
          qb.must(QueryBuilders.matchQuery(key,filedContentMap.get(key)));
        }
      dq.setQuery(qb);;
      elasticsearchTemplate.delete(dq, getEntityClass());;
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
  /**
   * 檢查健康狀態
   
   * @return
   */
  public boolean ping() {
    try {
      ActionFuture<ClusterHealthResponse> health = esClient.admin()
          .cluster().health(new ClusterHealthRequest());
      ClusterHealthStatus status = health.actionGet().getStatus();
      if (status.value() == ClusterHealthStatus.RED.value()) {
        throw new RuntimeException(
            "elasticsearch cluster health status is red.");
      }
      return true;
    } catch (Exception e) {
      logger.error("ping elasticsearch error.", e);
      return false;
    }
  }
 
  /**
   * 條件查詢
   
   * @param searchfields
   *      查詢字段
   * @param filedContentMap
   *      字段和查詢內容
   * @param sortField
   *      排序 字段
   * @param order
   *      排序
   * @param from
   * @param size
   * @return
   */
  @Override
  public BasePage<T> queryPage(Map<String,Object> filedContentMap, final List<String> heightFields, String sortField, SortOrder order, BasePage<T>basePage) {
     
    Field[] hfields=new Field[0];
    if(heightFields!=null)
    {
      hfields = new Field[heightFields.size()];
      for (int i = 0; i < heightFields.size(); i++) {
        hfields[i] = new HighlightBuilder.Field(heightFields.get(i)).preTags("<em style='color:red'>").postTags("</em>").fragmentSize(250);
      }
    }
    NativeSearchQueryBuilder nsb = new NativeSearchQueryBuilder().withHighlightFields(hfields);//高亮字段
    if (sortField != null && order != null)//排序
      nsb.withSort(new FieldSortBuilder(sortField).ignoreUnmapped(true).order(order));
    if (basePage != null)//分頁
      nsb.withPageable(new PageRequest(basePage.getPageNo(), basePage.getPageSize()));
    BoolQueryBuilder qb=QueryBuilders. boolQuery();
    for (String key : filedContentMap.keySet()) {//字段查詢
      qb.must(QueryBuilders.matchQuery(key,filedContentMap.get(key)));
       
    }
    //userKey=78e48b85e94911e0d285f4eec990d556
    //fa6e9c5bb24a21807c59e5fd3b609e12
    nsb.withQuery(qb);
    SearchQuery searchQuery = nsb.build();//查詢建立
 
    Page<T> page = null;
    if (heightFields!=null&&heightFields.size() > 0) {//如果設置高亮
      page = elasticsearchTemplate.queryForPage(searchQuery,
          getEntityClass(), new SearchResultMapper() {
            @SuppressWarnings("unchecked")
            @Override
            public <T> Page<T> mapResults(SearchResponse response,Class<T> clazz, Pageable pageable) {
              List<T> chunk = new ArrayList<T>();
              for (SearchHit searchHit : response.getHits()) {
                if (response.getHits().getHits().length <= 0) {
                  return null;
                }
 
                Map<String, Object> entityMap = searchHit.getSource();
                for (String highName : heightFields) {
                  Text text[]=searchHit.getHighlightFields().get(highName).fragments();
                  if(text.length>0)
                  {
                    String highValue = searchHit.getHighlightFields().get(highName).fragments()[0].toString();
                    entityMap.put(highName, highValue);
                  }
                }
                chunk.add((T) PropertyHelper.getFansheObj(
                    getEntityClass(), entityMap));
              }
              if (chunk.size() > 0) {
                return new PageImpl<T>((List<T>) chunk);
              }
              return new PageImpl<T>(new ArrayList<T>());
            }
 
          });
    } else//如果不設置高亮
    {
      logger.info("#################"+qb.toString());
      page = elasticsearchTemplate.queryForPage(searchQuery,getEntityClass());
    }
     
 
  // List<T> ts = page.getContent();
 
    basePage.setTotalRecord(page.getTotalElements());
    basePage.setResults(page.getContent());
    return basePage;
  }
 
   
  @Override
  public List<T> queryList(Map<String, Object> filedContentMap,final List<String> heightFields, String sortField, SortOrder order) {
    Field[] hfields=new Field[0];
    if(heightFields!=null)
    {
      hfields = new Field[heightFields.size()];
      for (int i = 0; i < heightFields.size(); i++) {
        //String o="{\"abc\" : \"[abc]\"}";
        hfields[i] = new HighlightBuilder.Field(heightFields.get(i)).preTags("<em>").postTags("</em>").fragmentSize(250);
      }
    }
    NativeSearchQueryBuilder nsb = new NativeSearchQueryBuilder().withHighlightFields(hfields);//高亮字段
    if (sortField != null && order != null)//排序
      nsb.withSort(new FieldSortBuilder(sortField).ignoreUnmapped(true).order(order));
    BoolQueryBuilder qb=QueryBuilders. boolQuery();
    for (String key : filedContentMap.keySet()) {//字段查詢
      qb.must(QueryBuilders.matchQuery(key,filedContentMap.get(key)));
       
    }
    nsb.withQuery(qb);
    SearchQuery searchQuery = nsb.build();//查詢建立
    Page<T> page = null;
    if (heightFields!=null&&heightFields.size() > 0) {//如果設置高亮
      page = elasticsearchTemplate.queryForPage(searchQuery,
          getEntityClass(), new SearchResultMapper() {
            @SuppressWarnings("unchecked")
            @Override
            public <T> Page<T> mapResults(SearchResponse response,Class<T> clazz, Pageable pageable) {
              List<T> chunk = new ArrayList<T>();
              for (SearchHit searchHit : response.getHits()) {
                if (response.getHits().getHits().length <= 0) {
                  return null;
                }
 
                Map<String, Object> entityMap = searchHit.getSource();
                for (String highName : heightFields) {
                  String highValue = searchHit.getHighlightFields().get(highName).fragments()[0].toString();
                  entityMap.put(highName, highValue);
                }
                chunk.add((T) PropertyHelper.getFansheObj(getEntityClass(), entityMap));
              }
              if (chunk.size() > 0) {
                return new PageImpl<T>((List<T>) chunk);
              }
              return null;
            }
 
          });
    } else//如果不設置高亮
      page = elasticsearchTemplate.queryForPage(searchQuery,getEntityClass());
     
    return page.getContent();
  }
  /**
   * 本類查詢
   
   * @param id
   * @return
   */
  public T queryById(String id) {
    StringQuery stringQuery = new StringQuery("id=" + id);
    T t = elasticsearchTemplate.queryForObject(stringQuery,
        getEntityClass());
    return t;
 
  }
 
   
   
  public ElasticsearchTemplate getElasticsearchTemplate() {
    return elasticsearchTemplate;
  }
 
 
  public Client getEsClient() {
    return esClient;
  }
 
 
 
  /**
   * 得到類型
   
   * @return
   */
  public abstract Class<T> getEntityClass();
  /**
   * 添加各自類的影射
   */
  public abstract void putClassMapping();
   
 
 
   
 
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:http://blog.csdn.net/u013378306/article/details/52185063

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 搡女人真爽免费午夜网站 | 日韩欧美久久 | 中文字幕在线视频观看 | 在线视频不卡一区 | 亚洲一区二区免费看 | 午夜精品影院 | 麻豆国产尤物av尤物在线观看 | 国产成人精品一区二区 | 精品国内 | 午夜小电影 | 久久亚洲国产精品 | 一级片黄片毛片 | 日韩精品久久久 | 中文字幕 在线观看 | 亚洲欧美日韩在线一区二区三区 | www.久久久| 精品国产一二三区 | a级毛片黄 | 啵啵羞羞影院 | 欧美一区三区 | 亚洲精品区 | 亚洲乱码日产精品一二三 | 欧美美女爱爱 | 精品中文一区 | 91成人在线 | 黄色一级片看看 | 色888www视频在线观看 | 国产精品久久久久久久久久久久久久 | 欧美中文一区二区三区 | 三级黄色片在线免费观看 | 欧美成人激情 | av网站有哪些 | 91.成人天堂一区 | 免费的av网站 | 日韩精品小视频 | 免费午夜在线视频 | 久久精品一区二区 | 视频一区二区国产 | 成人综合视频网 | 久久久久久久免费 | 免费激情 |