elasticsearch学习之旅

刚到公司,被安排接手一个基于elasticsearch做搜索服务的项目,第一次接触elasticsearch,作为学习经历,分享记录一下............

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

elasticsearch简介

   ElasticSearch是一个基于Lucene的搜索服务器,同大名鼎鼎的solr类似,也是一个开源企业搜索平台,在实时搜索方面具有比solr更强悍的性能,它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎,这里不做过多介绍。

elasticsearch安装

  首先到官网上下载elasticsearch,https://www.elastic.co/downloads/elasticsearch ,下载zip文件,解压的自己的目录,进入到bin目录,windows下直接点击elasticsearch.bat启动elasticsearch,在浏览器地址栏直接输入localhost:9200/_cat/health?v 进行测试,当看到

epoch timestamp cluster status node.total node.data shards pri relo init unassign

1394735289 14:28:09 elasticsearch green 1 1 0 0 0 0 0

恭喜你,这时候elasticsearch 已经可以正常工作了奋斗

elasticsearch使用

由于公司项目是基于java开发的,所以这里只说java的部分,为了简化步骤,这里基于maven构建项目,在pom.xml文件中添加

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

新建一个ESUtil的class

获取cilent Client client = TransportClient.builder().build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host1"), 9300))

构建索引 String json = "{" + "\"user\":\"kimchy\"," + "\"postDate\":\"2013-01-30\"," + "\"message\":\"trying out Elasticsearch\"" + "}";

IndexResponse response = client.prepareIndex("twitter", "tweet").setSource(json).get();

// Add transport addresses and do something with the client...
// Index name
String _index = response.getIndex();
// Type name
String _type = response.getType();
// Document ID (generated or not)
String _id = response.getId();
// Version (if it's the first time you index this document, you will
// get: 1)
long _version = response.getVersion();
// isCreated() is true if the document is a new one, false if it has
// been updated
boolean created = response.isCreated();
System.out.println("esinfo : " + _index + "  " + _type + "  " + _id + "  " + _version + "  " + created);

重点来了!!!我们最需要的搜索功能

SearchResponse searchResponse = client.prepareSearch().execute().actionGet();
for (SearchHit hit : searchResponse.getHits().getHits()) {
System.out.println("search result is:" + hit.getSourceAsString());
}

  到这里,elasticsearch的一个简单入门操作就算完成了!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值