public List<String> autocomplete(String prefix, int limit) { SearchRequestBuilder builder = new SearchRequestBuilder(factory.client()); builder.setIndices(Constants.INDEX).setTypes(Constants.TYPE); builder.setSearchType(SearchType.DEFAULT); builder.setFrom(0).setSize(limit).setExplain(IS_EXPLAIN); QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery("title", prefix); builder.setQuery(queryBuilder.toString()); logger.info("Search qeury"); logger.info(builder.toString()); SearchResponse sr = builder.execute().actionGet(); logger.info("Search response"); logger.info(sr.toString()); Iterator<SearchHit> it = sr.getHits().iterator(); while (it.hasNext()) { SearchHit hit = it.next(); hit.getSource(); } return Arrays.asList("a", "b", "c"); }
public Iterator<Blog> search(String keyword, int start, int size) { SearchRequestBuilder builder = new SearchRequestBuilder(factory.client()); builder.setIndices(Constants.INDEX).setTypes(Constants.TYPE); builder.setSearchType(SearchType.DEFAULT); builder.setFrom(start).setSize(size).setExplain(IS_EXPLAIN); BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().minimumNumberShouldMatch(1); queryBuilder.should(QueryBuilders.matchPhraseQuery("title", keyword)); queryBuilder.should(QueryBuilders.matchPhraseQuery("content", keyword)); queryBuilder.should(QueryBuilders.matchPhraseQuery("createPlace", keyword)); builder.setQuery(queryBuilder.toString()); logger.info("Search qeury"); logger.info(builder.toString()); SearchResponse sr = builder.execute().actionGet(); logger.info("Search response"); logger.info(sr.toString()); try { return new IteratorImpl<Blog>( sr.getHits().iterator(), Blog.class.getConstructor(SearchHit.class)); } catch (NoSuchMethodException | SecurityException e) { throw new RuntimeException(e); } }