刚到公司,被安排接手一个基于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的一个简单入门操作就算完成了!