elasticsearch 初学入门

初学elasticsearch,查阅无数资料终得运行成功,本文环境基于Java、Windows。

  1. elasticsearch版本:5.0.1,下载ZIP包,地址:点击打开链接

  2. 下载后解压到C:\elasticsearch-5.0.1
  3. 运行elasticsearch.bat,就在本机开启一个elasticsearch节点
  4. 浏览器访问 http://localhost:9200/ ,如果能够正常访问,说明该节点配置成功。
  5. 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();


	}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章