一而再_再而三

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

package com.huaji.shtel.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import com.huaji.shtel.base.BusinessException;
import com.huaji.shtel.base.EsClientBuilder;

/**
* @ClassName: ElasticSearchUtils
* @Description:ES工具类
* @author:dmy
* @date:2017年12月8日 下午2:10:37
*/
public class ElasticSearchUtils {

Logger logger=Logger.getLogger(ElasticSearchUtils.class);

private static TransportClient client=new EsClientBuilder().getTransportClient() ;

//创建索引库
public static boolean createSource(String indexName) throws Exception{
  if (isIndexExists(indexName)) {
    throw new BusinessException("该索引库已存在");
  }
  CreateIndexRequest cIndexRequest = new CreateIndexRequest(indexName);
  CreateIndexResponse cIndexResponse =
  client.admin().indices().create(cIndexRequest).actionGet();
  if (cIndexResponse.isAcknowledged()) {
    return true;
  } else {
    return false;
  }
}

//根据库名删除索引库
public static void deleteSourceByIndexName(String indexName) throws Exception{
  // DeleteIndexResponse dResponse =
  client.admin().indices().prepareDelete(indexName).execute().actionGet();
  // if(dResponse.isAcknowledged()){
    // return true;
  // }else{
    // return false;
  // }
}

//判断该索引库是否存在
private static boolean isIndexExists(String indexName) throws Exception{
  IndicesExistsRequest inExistsRequest = new IndicesExistsRequest(indexName);
  IndicesExistsResponse inExistsResponse=client.admin().indices().exists(inExistsRequest).actionGet();
  if(inExistsResponse.isExists()){
    return true;
  }else{
    return false;
  }
}

//索引库创建索引数据
public static void createIndex(String indexName,String type,String id,Map<String,String> map) throws Exception{
  // IndexResponse i=
  client.prepareIndex(indexName, type, id).setSource(map).get();
  // if(i.isFragment()){
    // return true;
  // }else{
    // return false;
  // }
}

//获取索引数据
public static Map<String, Object> getIndexData(String indexName,String type,String id) throws Exception{
  //setOperationThreaded(false)控制线程安全
  GetResponse response = client.prepareGet(indexName,type,id).setOperationThreaded(false).get();
  return response.getSource();
}

//修改索引数据
public void updataIndexData(String indexName,String type,String id,Map<String,Object> map) throws Exception{
  UpdateRequest uRequest = new UpdateRequest();
  uRequest.index(indexName);
  uRequest.type(type);
  uRequest.id(id);
  uRequest.doc(map);
  UpdateResponse s=client.update(uRequest).get();
  System.out.println(s);
}

//删除索引
public static void deleteIndexData(String indexName,String type,String id) throws Exception{
  // DeleteResponse response=
  client.prepareDelete(indexName, type, id).get();
  // Result result=response.getResult();
  // if(result.name().equals("DELETED")){
    // return true;
  // }else{
    // return false;
  // }
}

//检索索引
public static List<Object> queryIndex(String indexName,String type,String value,String...filedNames){
  MultiMatchQueryBuilder mmqb= QueryBuilders.multiMatchQuery(value,filedNames);
  SearchResponse response = client.prepareSearch(indexName)
  .setTypes(type).setQuery(mmqb).execute().actionGet();
  SearchHits hits = response.getHits();
  List<Object> list=new ArrayList<>();
  SearchHit[] searchHists =hits.getHits();
  if(searchHists.length>0){
    for(SearchHit hit:searchHists){
      list.add(hit.getSource());
    }
  }
  return list;
  }
}

 

//如果需要交给spring管理

//新建elasticsearch配置文件通过ref配到spring需要加载的文件去

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache-4.2.xsd">
      <context:component-scan base-package="com.huaji.shtel.base"/>
    <bean id="configProperties"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="locations">
        <list>
          <value>classpath*:elasticsearch.properties</value>
        </list>
      </property>
    </bean> 
    <bean id="client" factory-bean="esClientBuilder" factory-method="init" destroy-method="close"/>
    <bean id="esClientBuilder" class="com.huaji.shtel.base.EsClientBuilder">
      <property name="clusterName" value="${elasticsearch.cluster-name}" />
      <property name="nodeIpInfo" value="${elasticsearch.cluster-nodes}" />
    </bean>
</beans>

//spring需要加载的文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- <context:property-placeholder location="classpath*:redis.properties;classpath*:jdbc.properties" /> -->

    <bean id="configProperties"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
      <list>
        <value>classpath*:jdbc.properties</value>
        <value>classpath*:redis.properties</value>
        <value>classpath*:elasticsearch.properties</value>
      </list>
    </property>
    </bean>
    <context:annotation-config />
    <!-- 配置component所在的包,自动加载需要管理的Bean -->
    <context:component-scan base-package="com.huaji">
    <!-- 不扫描控制器 -->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <import resource="spring-database.xml" />
    <!-- <import resource="spring-cache.xml" />  -->
    <import resource="spring-shiro.xml" />
    <import resource="elasticsearch.xml" />
</beans>

//maven管理需要导入jar包

  

<!-- ElasticSearch客户端 -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.4.0</version>
</dependency>

<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.4.0</version>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>

//spring集成

package com.huaji.shtel.base;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

public class EsClientBuilder {

  /**集群的名称*/
  private String clusterName;
  /**节点的信息*/
  private String nodeIpInfo;
  /**客户端*/
  private TransportClient client;
  //客户端初始化
  public Client init(){
    //设置集群的名字
    Settings settings = Settings.builder()
    .put("cluster.name", clusterName)
    .build();
    //创建集群client并添加集群节点地址
    client = new PreBuiltTransportClient(settings);
    Map<String, Integer> nodeMap = parseNodeIpInfo();
      for (Map.Entry<String,Integer> entry : nodeMap.entrySet()){
        try {
          client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(entry.getKey()), entry.getValue()));
        } catch (UnknownHostException e) {
          e.printStackTrace();
      }
  }
  return client;
}

/**
* 解析节点IP信息,多个节点用逗号隔开,IP和端口用冒号隔开
*
* @return
*/
private Map<String, Integer> parseNodeIpInfo(){
  String[] nodeIpInfoArr = nodeIpInfo.split(",");
  Map<String, Integer> map = new HashMap<String, Integer>();
  for (String ipInfo : nodeIpInfoArr){
    String[] ipInfoArr = ipInfo.split(":");
    map.put(ipInfoArr[0], Integer.parseInt(ipInfoArr[1]));
  }
  return map;
}

public TransportClient getTransportClient(){
  return client;
}

public String getClusterName() {
  return clusterName;
}

public void setClusterName(String clusterName) {
  this.clusterName = clusterName;
}

public String getNodeIpInfo() {
  return nodeIpInfo;
}

public void setNodeIpInfo(String nodeIpInfo) {
  this.nodeIpInfo = nodeIpInfo;
}

}

//elasticsearch properties文件

#服务器的ip和端口号
elasticsearch.cluster-nodes=127.0.0.1:9300
#集群的名称
elasticsearch.cluster-name=dmy

 测试方法采用的是elasticsearch-5.5.1 与elasticsearch-head-master 并没用到elasticsearch-analysis-pinyin-5.5.1

posted on 2017-12-26 17:10  一而再_再而三  阅读(636)  评论(0)    收藏  举报