设为首页 收藏本站
查看: 812|回复: 0

[经验分享] elasticsearch简单JavaAPI总结

[复制链接]

尚未签到

发表于 2019-1-28 14:07:52 | 显示全部楼层 |阅读模式
  基于员工信息的CRUD操作

/**
* 员工增删改查的应用程序
*
* @author Administrator
*
*/
public class EmployeeCRUDApp {
@SuppressWarnings({ "unchecked", "resource" })
public static void main(String[] args) throws Exception {
// 先构建client
Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
// createEmployee(client);
// getEmployee(client);
// updateEmployee(client);
// deleteEmployee(client);
client.close();
}
/**
* 创建员工信息(创建一个document)
*
* @param client
*/
private static void createEmployee(TransportClient client) throws Exception {
IndexResponse response = client.prepareIndex("company", "employee", "1")
.setSource(XContentFactory.jsonBuilder().startObject().field("name", "jack").field("age", 27)
.field("position", "technique").field("country", "china").field("join_date", "2017-01-01")
.field("salary", 10000).endObject())
.get();
System.out.println(response.getResult());
}
/**
* 获取员工信息
*
* @param client
* @throws Exception
*/
private static void getEmployee(TransportClient client) throws Exception {
GetResponse response = client.prepareGet("company", "employee", "1").get();
System.out.println(response.getSourceAsString());
}
/**
* 修改员工信息
*
* @param client
* @throws Exception
*/
private static void updateEmployee(TransportClient client) throws Exception {
UpdateResponse response = client.prepareUpdate("company", "employee", "1")
.setDoc(XContentFactory.jsonBuilder().startObject().field("position", "technique manager").endObject())
.get();
System.out.println(response.getResult());
}
/**
* 删除 员工信息
*
* @param client
* @throws Exception
*/
private static void deleteEmployee(TransportClient client) throws Exception {
DeleteResponse response = client.prepareDelete("company", "employee", "1").get();
System.out.println(response.getResult());
}
}  基于员工信息的查询操作

/**
* 员工搜索应用程序
*
* @author Administrator
*
*/
public class EmployeeSearchApp {
@SuppressWarnings({ "unchecked", "resource" })
public static void main(String[] args) throws Exception {
Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
prepareData(client);
// executeSearch(client);
client.close();
}
/**
* 执行搜索操作
*
* @param client
*/
private static void executeSearch(TransportClient client) {
SearchResponse response = client.prepareSearch("company").setTypes("employee")
.setQuery(QueryBuilders.matchQuery("position", "technique"))
.setPostFilter(QueryBuilders.rangeQuery("age").from(30).to(40)).setFrom(0).setSize(1).get();
SearchHit[] searchHits = response.getHits().getHits();
for (int i = 0; i < searchHits.length; i++) {
System.out.println(searchHits.getSourceAsString());
}
}
/**
* 准备数据
*
* @param client
*/
private static void prepareData(TransportClient client) throws Exception {
client.prepareIndex(&quot;company&quot;, &quot;employee&quot;, &quot;1&quot;)
.setSource(XContentFactory.jsonBuilder().startObject().field(&quot;name&quot;, &quot;jack&quot;).field(&quot;age&quot;, 27)
.field(&quot;position&quot;, &quot;technique software&quot;).field(&quot;country&quot;, &quot;china&quot;)
.field(&quot;join_date&quot;, &quot;2017-01-01&quot;).field(&quot;salary&quot;, 10000).endObject())
.get();
client.prepareIndex(&quot;company&quot;, &quot;employee&quot;, &quot;2&quot;)
.setSource(XContentFactory.jsonBuilder().startObject().field(&quot;name&quot;, &quot;marry&quot;).field(&quot;age&quot;, 35)
.field(&quot;position&quot;, &quot;technique manager&quot;).field(&quot;country&quot;, &quot;china&quot;)
.field(&quot;join_date&quot;, &quot;2017-01-01&quot;).field(&quot;salary&quot;, 12000).endObject())
.get();
client.prepareIndex(&quot;company&quot;, &quot;employee&quot;, &quot;3&quot;)
.setSource(XContentFactory.jsonBuilder().startObject().field(&quot;name&quot;, &quot;tom&quot;).field(&quot;age&quot;, 32)
.field(&quot;position&quot;, &quot;senior technique software&quot;).field(&quot;country&quot;, &quot;china&quot;)
.field(&quot;join_date&quot;, &quot;2016-01-01&quot;).field(&quot;salary&quot;, 11000).endObject())
.get();
client.prepareIndex(&quot;company&quot;, &quot;employee&quot;, &quot;4&quot;)
.setSource(XContentFactory.jsonBuilder().startObject().field(&quot;name&quot;, &quot;jen&quot;).field(&quot;age&quot;, 25)
.field(&quot;position&quot;, &quot;junior finance&quot;).field(&quot;country&quot;, &quot;usa&quot;).field(&quot;join_date&quot;, &quot;2016-01-01&quot;)
.field(&quot;salary&quot;, 7000).endObject())
.get();
client.prepareIndex(&quot;company&quot;, &quot;employee&quot;, &quot;5&quot;)
.setSource(XContentFactory.jsonBuilder().startObject().field(&quot;name&quot;, &quot;mike&quot;).field(&quot;age&quot;, 37)
.field(&quot;position&quot;, &quot;finance manager&quot;).field(&quot;country&quot;, &quot;usa&quot;).field(&quot;join_date&quot;, &quot;2015-01-01&quot;)
.field(&quot;salary&quot;, 15000).endObject())
.get();
}
}  基于员工新的聚合查询操作
/**
* 员工聚合分析应用程序
*
* @author Administrator
*
*/
public class EmployeeAggrApp {
@SuppressWarnings({ &quot;unchecked&quot;, &quot;resource&quot; })
public static void main(String[] args) throws Exception {
Settings settings = Settings.builder().put(&quot;cluster.name&quot;, &quot;elasticsearch&quot;).build();
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(&quot;localhost&quot;), 9300));
SearchResponse searchResponse = client.prepareSearch(&quot;company&quot;)
.addAggregation(AggregationBuilders.terms(&quot;group_by_country&quot;).field(&quot;country&quot;)
.subAggregation(AggregationBuilders.dateHistogram(&quot;group_by_join_date&quot;).field(&quot;join_date&quot;)
.dateHistogramInterval(DateHistogramInterval.YEAR)
.subAggregation(AggregationBuilders.avg(&quot;avg_salary&quot;).field(&quot;salary&quot;))))
.execute().actionGet();
Map aggrMap = searchResponse.getAggregations().asMap();
StringTerms groupByCountry = (StringTerms) aggrMap.get(&quot;group_by_country&quot;);
Iterator groupByCountryBucketIterator = groupByCountry.getBuckets().iterator();
while (groupByCountryBucketIterator.hasNext()) {
Bucket groupByCountryBucket = groupByCountryBucketIterator.next();
System.out.println(groupByCountryBucket.getKey() + &quot;:&quot; + groupByCountryBucket.getDocCount());
Histogram groupByJoinDate = (Histogram) groupByCountryBucket.getAggregations().asMap()
.get(&quot;group_by_join_date&quot;);
Iterator groupByJoinDateBucketIterator = groupByJoinDate
.getBuckets().iterator();
while (groupByJoinDateBucketIterator.hasNext()) {
org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Bucket groupByJoinDateBucket = groupByJoinDateBucketIterator
.next();
System.out.println(groupByJoinDateBucket.getKey() + &quot;:&quot; + groupByJoinDateBucket.getDocCount());
Avg avg = (Avg) groupByJoinDateBucket.getAggregations().asMap().get(&quot;avg_salary&quot;);
System.out.println(avg.getValue());
}
}
client.close();
}
}  注:聚合查询的时候可能出现问题:fielddata需要变为true,这个时候需要手动添加mapping
GET /company/_mapping/employee
{
  &quot;company&quot;: {
    &quot;mappings&quot;: {
      &quot;employee&quot;: {
        &quot;properties&quot;: {
          &quot;age&quot;: {
            &quot;type&quot;: &quot;long&quot;
          },
          &quot;country&quot;: {
            &quot;type&quot;: &quot;text&quot;,
            &quot;fields&quot;: {
              &quot;keyword&quot;: {
                &quot;type&quot;: &quot;keyword&quot;,
                &quot;ignore_above&quot;: 256
              }
            }
          },
          &quot;join_date&quot;: {
            &quot;type&quot;: &quot;date&quot;
          },
          &quot;name&quot;: {
            &quot;type&quot;: &quot;text&quot;,
            &quot;fields&quot;: {
              &quot;keyword&quot;: {
                &quot;type&quot;: &quot;keyword&quot;,
                &quot;ignore_above&quot;: 256
              }
            }
          },
          &quot;position&quot;: {
            &quot;type&quot;: &quot;text&quot;,
            &quot;fields&quot;: {
              &quot;keyword&quot;: {
                &quot;type&quot;: &quot;keyword&quot;,
                &quot;ignore_above&quot;: 256
              }
            }
          },
          &quot;salary&quot;: {
            &quot;type&quot;: &quot;long&quot;
          }
        }
      }
    }
  }
}
Delete /company
上面查出来以后进行截取,修改&quot;fielddata&quot;: true
PUT /company
{
  &quot;mappings&quot;: {
      &quot;employee&quot;: {
        &quot;properties&quot;: {
          &quot;age&quot;: {
            &quot;type&quot;: &quot;long&quot;
          },
          &quot;country&quot;: {
            &quot;type&quot;: &quot;text&quot;,
            &quot;fields&quot;: {
              &quot;keyword&quot;: {
                &quot;type&quot;: &quot;keyword&quot;,
                &quot;ignore_above&quot;: 256
              }
            },
            &quot;fielddata&quot;: true
          },
          &quot;join_date&quot;: {
            &quot;type&quot;: &quot;date&quot;
          },
          &quot;name&quot;: {
            &quot;type&quot;: &quot;text&quot;,
            &quot;fields&quot;: {
              &quot;keyword&quot;: {
                &quot;type&quot;: &quot;keyword&quot;,
                &quot;ignore_above&quot;: 256
              }
            }
          },
          &quot;position&quot;: {
            &quot;type&quot;: &quot;text&quot;,
            &quot;fields&quot;: {
              &quot;keyword&quot;: {
                &quot;type&quot;: &quot;keyword&quot;,
                &quot;ignore_above&quot;: 256
              }
            }
          },
          &quot;salary&quot;: {
            &quot;type&quot;: &quot;long&quot;
          }
        }
      }
    }
}  elasticsearch-5.2.0获取代码
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.stereotype.Component;
import com.ad.utils.ConfigUtil;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by wangyunpeng on 2017/8/5.
*/
@Component
public class ElasticSearchClient {
    @Resource(type=ConfigUtil.class)
    private ConfigUtil configUtil;
    private Map clientMap = new ConcurrentHashMap();
    /*1.@PostConstruct说明
    被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。
2.@PreConstruct说明
    被@PreConstruct修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreConstruct修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前。
   */
    @PostConstruct
    public void init() {
        init(configUtil.clusterName, configUtil.clusterIpAddress);
        //init(configUtil.clusterName2, configUtil.clusterIpAddress2);
    }
    private void init(String clusterName, String clusterIpAddress){
    try {
    Settings settings = Settings.builder()
        .put(&quot;cluster.name&quot;, clusterName)
        .build();
        addClient(settings, getAllAddress(clusterIpAddress));
    }catch(Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 得所有的地址端口
     * @param ips
     * @return
     * @throws Exception
     */
    public List getAllAddress(String ips)throws Exception {
        List addressList = new ArrayList();
        if(StringUtils.isNotBlank(ips)&&ips.contains(&quot;,&quot;)){
            String[] ipaddr=ips.split(&quot;,&quot;);
            for (int i=0;i

    org.elasticsearch.client
    transport
    6.0.0
  测试代码:
import java.io.IOException;
import java.util.UUID;
import javax.annotation.Resource;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.ad.base.AlbumIndexField;
import com.ad.utils.ConfigUtil;
import com.ad.utils.ExceptionUtil;
import net.sf.json.JSONObject;
@Component
public class ElasticSaveServiceImpl implements ElasticSaveService {
private static final Logger logger = LoggerFactory.getLogger(ElasticSearchServiceImpl.class);
    @Resource(type = ElasticSearchClient.class)
    private ElasticSearchClient elasticSearchClient;
    @Resource(type = ConfigUtil.class)
    private ConfigUtil configUtil;
    /**
     * @return
     */
    public Client getClient(String clusterName) {
        try {
            return elasticSearchClient.getClient(clusterName);
        } catch (Exception e) {
            logger.error(&quot;ES获取client失败 :&quot; + ExceptionUtil.stackTrace(e));
            return null;
        }
    }
@Override
public void executeSave(String clusterName, String json1) {
JSONObject json = JSONObject.fromObject(json1);
String documentId = (UUID.randomUUID().toString().replaceAll(&quot;-&quot;, &quot;&quot;));
IndexResponse response;
try {
response = this.getClient(clusterName).prepareIndex(configUtil.indexName, configUtil.indexType, documentId)
.setSource(XContentFactory.jsonBuilder()
.startObject()
.field(AlbumIndexField.FID, json.getString(&quot;fid&quot;))
.endObject())
.get();
} catch (IOException e) {
logger.error(&quot;===AdInfoConsumer consumer is exception&quot;, e);
//e.printStackTrace();
}
}
}



运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-668786-1-1.html 上篇帖子: Elasticsearch安装篇 下篇帖子: Golang elasticsearch 对接问题
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表