Java Code Examples for org.elasticsearch.search.suggest.Suggest.Suggestion.Entry

The following examples show how to use org.elasticsearch.search.suggest.Suggest.Suggestion.Entry. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Elasticsearch   Source File: Suggest.java    License: Apache License 2.0 5 votes vote down vote up
public <T extends Suggestion<? extends Entry<? extends Option>>> T getSuggestion(String name) {
    if (suggestions.isEmpty() || name == null) {
        return null;
    } else if (suggestions.size() == 1) {
      return (T) (name.equals(suggestions.get(0).name) ? suggestions.get(0) : null);
    } else if (this.suggestMap == null) {
        suggestMap = new HashMap<>();
        for (Suggest.Suggestion<? extends Entry<? extends Option>> item : suggestions) {
            suggestMap.put(item.getName(), item);
        }
    }
    return (T) suggestMap.get(name);
}
 
Example 2
Source Project: Elasticsearch   Source File: Suggest.java    License: Apache License 2.0 5 votes vote down vote up
public static Map<String, List<Suggest.Suggestion>> group(Map<String, List<Suggest.Suggestion>> groupedSuggestions, Suggest suggest) {
    for (Suggestion<? extends Entry<? extends Option>> suggestion : suggest) {
        List<Suggestion> list = groupedSuggestions.get(suggestion.getName());
        if (list == null) {
            list = new ArrayList<>();
            groupedSuggestions.put(suggestion.getName(), list);
        }
        list.add(suggestion);
    }
    return groupedSuggestions;
}
 
Example 3
Source Project: Elasticsearch   Source File: Suggest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(StreamOutput out) throws IOException {
    innerWriteTo(out);
    out.writeVInt(entries.size());
    for (Entry<?> entry : entries) {
        entry.writeTo(out);
    }
}
 
Example 4
Source Project: Elasticsearch   Source File: Suggest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startArray(name);
    for (Entry<?> entry : entries) {
        entry.toXContent(builder, params);
    }
    builder.endArray();
    return builder;
}
 
Example 5
Source Project: Elasticsearch   Source File: Suggest.java    License: Apache License 2.0 5 votes vote down vote up
protected <T extends Entry<O>> Entry<O> reduce(List<T> toReduce) {
    if (toReduce.size() == 1) {
        return toReduce.get(0);
    }
    final Map<O, O> entries = new HashMap<>();
    Entry<O> leader = toReduce.get(0);
    for (Entry<O> entry : toReduce) {
        if (!leader.text.equals(entry.text)) {
            throw new IllegalStateException("Can't merge suggest entries, this might be caused by suggest calls " +
                    "across multiple indices with different analysis chains. Suggest entries have different text actual [" +
                    entry.text + "] expected [" + leader.text +"]");
        }
        assert leader.offset == entry.offset;
        assert leader.length == entry.length;
        leader.merge(entry);
        for (O option : entry) {
            O merger = entries.get(option);
            if (merger == null) {
                entries.put(option, option);
            } else {
                merger.mergeInto(option);
            }
        }
    }
    leader.options.clear();
    for (O option: entries.keySet()) {
        leader.addOption(option);
    }
    return leader;
}
 
Example 6
Source Project: Elasticsearch   Source File: Suggest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Entry<?> entry = (Entry<?>) o;

    if (length != entry.length) return false;
    if (offset != entry.offset) return false;
    if (!this.text.equals(entry.text)) return false;

    return true;
}
 
Example 7
Source Project: es-service-parent   Source File: EsSearch.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 无奈es的版本太低了,无法在建议器中做过滤操作(笔者es版本1.1),在更高版本的es中可以通过Context Suggester做过滤
 * 
 * @param indices
 * @param suggestQuery
 * @return
 */
@SuppressWarnings({ "unchecked" })
private static List<Map<String, Object>> getCompletionSuggest(String indices,
        SuggestQuery suggestQuery) {
    // 查询体
    CompletionSuggestionFuzzyBuilder suggestionsBuilder = new CompletionSuggestionFuzzyBuilder(
            suggestQuery.suggestName);
    suggestionsBuilder.setFuzziness(Fuzziness.build(suggestQuery.getFuzziness()));
    suggestionsBuilder.text(suggestQuery.getText());
    suggestionsBuilder.field(suggestQuery.getField());
    suggestionsBuilder.size(suggestQuery.getSize());

    SuggestRequestBuilder suggestRequestBuilder = ESClient.getClient()
            .prepareSuggest(indices.split(",")).addSuggestion(suggestionsBuilder);
    SuggestResponse resp = suggestRequestBuilder.execute().actionGet();
    // 查询结果
    List<? extends Entry<? extends Option>> entries = (List<? extends Entry<? extends Option>>) resp
            .getSuggest().getSuggestion(suggestQuery.suggestName).getEntries();
    if (entries == null) {
        return Lists.newArrayList();
    }
    List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    for (Entry<? extends Option> e : entries) {
        for (Option option : e) {
            Map<String, Object> map_payload = option.getPayloadAsMap();
            map_payload.put("NAME", option.getText().toString());
            result.add(map_payload);
        }
    }

    // 调试模式
    if (Constants.isDebug) {
        logger.info(suggestRequestBuilder.toString());
        logger.info(suggestionsBuilder.toString());
        logger.info(JsonUtil.toJson(result));
    }
    return result;
}
 
Example 8
Source Project: elasticsearch-jest-example   Source File: TransportClient.java    License: MIT License 5 votes vote down vote up
private static void suggest(){
		Client client = createTransportClient();
		
//		CompletionSuggestionBuilder completionSuggestion = new CompletionSuggestionBuilder("suggestions");
//		completionSuggestion.field("text");
//		completionSuggestion.text("园");
//		completionSuggestion.size(10);
//		
//		SuggestRequestBuilder suggestRequestBuilder = client.prepareSuggest("article");
//		suggestRequestBuilder.addSuggestion(completionSuggestion);
//		SuggestResponse suggestResponse = suggestRequestBuilder.execute().actionGet();
//		
//		Suggestion<? extends Entry<? extends Option>> suggestion = suggestResponse.getSuggest().getSuggestion("suggestions");
//		for(Entry<? extends Option> entry:suggestion){
//			for (Option option : entry) {
//				System.out.println(option.getText().string());
//			}
//		}
		
		TermSuggestionBuilder termSuggestionBuilder = new TermSuggestionBuilder("suggest"); 
		termSuggestionBuilder.text("编程");
		termSuggestionBuilder.field("desc");
		TermSuggestion termSuggestion = client.prepareSuggest("book")
				.addSuggestion(termSuggestionBuilder)
				.execute()
				.actionGet()
				.getSuggest()
				.getSuggestion("suggest");
		Suggestion<? extends Entry<? extends Option>> suggestion = termSuggestion;
		for(Entry<? extends Option> entry:suggestion){
			for (Option option : entry) {
				System.out.println(option.getText().string());
			}
		}
		
	}
 
Example 9
Source Project: Elasticsearch   Source File: Suggest.java    License: Apache License 2.0 4 votes vote down vote up
public Suggest(List<Suggestion<? extends Entry<? extends Option>>> suggestions) {
    this(null, suggestions);
}
 
Example 10
Source Project: Elasticsearch   Source File: Suggest.java    License: Apache License 2.0 4 votes vote down vote up
public Suggest(XContentBuilderString name, List<Suggestion<? extends Entry<? extends Option>>> suggestions) {
    this.name = name;
    this.suggestions = suggestions;
}
 
Example 11
Source Project: Elasticsearch   Source File: Suggest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Iterator<Suggestion<? extends Entry<? extends Option>>> iterator() {
    return suggestions.iterator();
}
 
Example 12
Source Project: Elasticsearch   Source File: Suggest.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Trims the number of options per suggest text term to the requested size.
 * For internal usage.
 */
public void trim() {
    for (Entry<?> entry : entries) {
        entry.trim(size);
    }
}
 
Example 13
Source Project: Elasticsearch   Source File: Suggest.java    License: Apache License 2.0 4 votes vote down vote up
protected T newEntry() {
    return (T)new Entry();
}
 
Example 14
Source Project: Elasticsearch   Source File: Suggest.java    License: Apache License 2.0 4 votes vote down vote up
public Entry(Text text, int offset, int length) {
    this.text = text;
    this.offset = offset;
    this.length = length;
    this.options = new ArrayList<>(5);
}
 
Example 15
Source Project: Elasticsearch   Source File: Suggest.java    License: Apache License 2.0 4 votes vote down vote up
public Entry() {
}
 
Example 16
Source Project: Elasticsearch   Source File: PhraseSuggester.java    License: Apache License 2.0 4 votes vote down vote up
private PhraseSuggestion.Entry buildResultEntry(PhraseSuggestionContext suggestion, CharsRefBuilder spare, double cutoffScore) {
    spare.copyUTF8Bytes(suggestion.getText());
    return new PhraseSuggestion.Entry(new Text(spare.toString()), 0, spare.length(), cutoffScore);
}
 
Example 17
Source Project: es-service-parent   Source File: EsSearch.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 搜索入口
 * 
 * @param request
 * @param timeout
 * @param timeUnit
 * @return
 */
public static EsResponse search(EsRequest request, int timeout, TimeUnit timeUnit) {
    // 索引
    String indexname = request.getIndexname();
    // 结束位置
    int size = request.getPs();
    // 开始位置
    int from = request.getPn() < 0 ? 0 : (request.getPn() - 1) * size;

    // 主查询体
    SearchRequestBuilder srb = ESClient.getClient().prepareSearch(indexname)
            .setTypes(request.getTypes().toArray(new String[] {})).setFrom(from).setSize(size)
            .setPreference(Constants.preference).setTimeout(new TimeValue(timeout, timeUnit));

    // 构造查询体
    EsQueryBuilder esQueryBuilder = new EsQueryBuilder(request);
    esQueryBuilder.makeFilterBuilder(srb);
    if (esQueryBuilder.makeQueryBuilder(srb) == null) {
        return new EsResponse();
    }

    // 处理返回字段
    if (!request.getSafeResultFileds().isEmpty()) {
        srb.addFields(request.getSafeResultFileds().toArray(new String[] {}));
    }
    // 高亮
    EsHighLight.setHighLight(srb, request.getSafeHighlightFields());
    // 排序
    EsSort.sortAdapter(srb, request.getSafeSortFileds());
    // 调试模式
    if (Constants.isDebug) {
        srb.setExplain(true);
        logger.info("\r\n" + srb.toString());
    }

    // 返回结果
    SearchResponse response = srb.execute().actionGet();
    List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    for (SearchHit hit : response.getHits()) {
        Map<String, Object> record = hit.getSource();
        if (record == null && (record = new HashMap<String, Object>()) != null) {
            for (Map.Entry<String, SearchHitField> e : hit.fields().entrySet()) {
                record.put(e.getKey(), e.getValue().getValue());
            }
        }
        record.put("ESSCORE", hit.getScore());
        // 高亮返回
        if (request.getSafeHighlightFields() != null) {
            record.putAll(EsHighLight.getHighlight(hit, request.getSafeHighlightFields()
                    .getFields()));
        }
        result.add(record);
    }

    // 调试模式
    if (Constants.isDebug) {
        logger.info("search result :{}", JsonUtil.toJson(result));
        logger.info("search TotalHits :{}", response.getHits().getTotalHits());
        logger.info("search TookInMillis :{}", response.getTookInMillis());
    }

    logger.info("search log for index:{},keys:{}", indexname, request.getAllValue());
    return new EsResponse((int) response.getHits().getTotalHits(), JsonUtil.toJson(result), 0);
}
 
Example 18
Source Project: Elasticsearch   Source File: Suggest.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Merge any extra fields for this subtype.
 */
protected void merge(Entry<O> other) {
}