ES JAVA API

ES 2.2.1 

初始化ES Client

public void init() {
		Settings settings = Settings.settingsBuilder()
				.put("cluster.name", "my-application").build();
		try {
			client = TransportClient
					.builder()
					.settings(settings)
					.build()
					.addTransportAddress(
					    new InetSocketTransportAddress(
                            InetAddress.getByName("localhost"),
                            9300));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

创建索引

public void createIndex() throws Exception {
		IndicesExistsResponse resp = client.admin().indices().
				prepareExists("estest").execute().actionGet();
		if(!resp.isExists()){
			client.admin().indices().prepareCreate("estest")
			.execute().actionGet();
		}
		Map<String, String> dataMap =new HashMap<String, String>();
		dataMap.put("title", "es yyyyy");
		dataMap.put("content", "hello china ,i love you");
		dataMap.put("url", "http://localhost:8999/ljidslaj.com");
		
		client.prepareIndex("estest", "htmlbean").setSource(dataMap).execute().actionGet();
		
		
		
	}

关键字查询

public void search() throws Exception {
		String kw ="love";
		
		
		MultiMatchQueryBuilder q =
				new MultiMatchQueryBuilder(kw, new String[]{"title","content"});
		
		SearchResponse resp = client.prepareSearch("estest")
				.setTypes("htmlbean")
				.setQuery(q)
				.addHighlightedField("title")
				.addHighlightedField("content")
				.setHighlighterFragmentSize(40)//设置显示结果中一个碎片段的长度
				.setHighlighterNumOfFragments(5)//设置显示结果中每个结果最多显示碎片段,每个碎片段之间用...隔开
				.setFrom(0)
				.setSize(10)
				.execute().actionGet();
		
		SearchHits hits= resp.getHits();
		for(SearchHit hit : hits.getHits()){
			String title,content,url = null;
			if(hit.getHighlightFields().get("title")==null){//title中没有包含关键字
				title=hit.getSource().get("title").toString();//获取原来的title(没有高亮的title)
			}else{
				title=hit.getHighlightFields()
				.get("title").getFragments()[0].toString();
			}
			
			if(hit.getHighlightFields().get("content")==null){//title中没有包含关键字
				content=hit.getSource().get("content").toString();//获取原来的title(没有高亮的title)
			}else{
				content=hit.getHighlightFields()
				.get("content").getFragments()[0].toString();
			}
			
			
			if(hit.getSource().get("url")!=null) {
				url = hit.getSource().get("url").toString();
			}
			
			System.out.println("title ==="+title);
			System.out.println("content ==="+content);
			System.out.println("url ==="+url);
			System.out.println();
		
		}
	}

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值