elasticsearch 初学入门
ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。官网:https://www.elastic.co/
初学elasticsearch,查阅无数资料终得运行成功,本文环境基于Java、Windows。
- elasticsearch版本:5.0.1,下载ZIP包,地址:https://www.elastic.co/downloads/elasticsearch。
- 下载后解压到C:\elasticsearch-5.0.1
- 运行elasticsearch.bat,就在本机开启一个elasticsearch节点
- 浏览器访问 http://localhost:9200/ ,如果能够正常访问,说明该节点配置成功。
- Java Maven 项目调用 elasticsearch API,直接贴代码
pom.xml文件详见 pom.xml
public static void main(String[] args) throws UnknownHostException {
@SuppressWarnings("resource")
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(
InetAddress.getByName("127.0.0.1"), 9300));
Map<String, Object> json = new HashMap<String, Object>();
json.put("user", "jack k");
json.put("postDate", "2016-11-23");
json.put("message", "es demo");
client.prepareIndex("twitter", "tweet", "1").setType("muti_field")
.setSource(json).execute().actionGet();
GetResponse response = client.prepareGet("twrite", "tweet", "1")
.execute().actionGet();
Map<String, Object> map = response.getSource();
Iterator<Entry<String, Object>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, Object> ent = iter.next();
System.out.println(ent.getKey() + "=" + ent.getValue());
}
QueryBuilder qb = QueryBuilders.matchQuery("user", "jack");
SearchResponse scrollResp = client.prepareSearch("twitter")
.setSearchType(SearchType.DEFAULT)
.setScroll(new TimeValue(60000)).setQuery(qb).setSize(100)
.execute().actionGet();
System.out.println("通过user字段查询:" + scrollResp);
System.out.println(
"通过user字段查询信息数量:" + scrollResp.getHits().getTotalHits());
for (SearchHit hit : scrollResp.getHits()) {
Iterator<Entry<String, Object>> rpItor = hit.getSource().entrySet()
.iterator();
while (rpItor.hasNext()) {
Entry<String, Object> rpEnt = rpItor.next();
System.out.println(rpEnt.getKey() + " : " + rpEnt.getValue());
}
}
client.close();
}
次写文章,如果问题敬请谅解指出,谢谢。小弟再此拜上。
相关文章