ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是第二流行的企业搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。
最近学习了一下ElasticSearch的Java API使用,简易代码如下:
package com.learn.test;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.action.index.IndexResponse;
import java.io.IOException;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
public class TestElastic
{
public static void main(String[] args)
{
UserModel user = new UserModel();
user.setId(1);
user.setName("李四");
user.setAge("101");
user.setSex("1231");
user.setTel("Tel");
String jsondata = toJson(user);
System.out.println("封装的json:"+jsondata);
Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "tang-elasticsearch").build();
Client client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress("192.168.15.1", 9300));
IndexResponse res = client.prepareIndex().setIndex("school").setType("class").setId("10").setSource(jsondata).execute().actionGet();
System.out.println("索引创建成功,版本号:"+res.getVersion());
client.close();
}
public static String toJson(Object o)
{
try
{
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(o);
}
catch (JsonProcessingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return "";
}
}