org.elasticsearch.search.suggest.Suggest.Suggestion.Entry.Option Java Examples

The following examples show how to use org.elasticsearch.search.suggest.Suggest.Suggestion.Entry.Option. 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 File: TermSuggestion.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public int compare(Suggestion.Entry.Option first, Suggestion.Entry.Option second) {

    // first criteria: the popularity
    int cmp = ((TermSuggestion.Entry.Option) second).getFreq() - ((TermSuggestion.Entry.Option) first).getFreq();
    if (cmp != 0) {
        return cmp;
    }

    // second criteria (if first criteria is equal): the distance
    cmp = Float.compare(second.getScore(), first.getScore());
    if (cmp != 0) {
        return cmp;
    }

    // third criteria: term text
    return first.getText().compareTo(second.getText());
}
 
Example #2
Source File: ElasticQueryBuilder.java    From vind with Apache License 2.0 6 votes vote down vote up
public static List<String> getSpellCheckedQuery(SearchResponse response) {
    final Map<String, Pair<String,Double>> spellcheck = Streams.stream(response.getSuggest().iterator())
            .map(e ->Pair.of(e.getName(),  e.getEntries().stream()
                    .map(word ->
                            word.getOptions().stream()
                                    .sorted(Comparator.comparingDouble(Option::getScore).reversed())
                                    .map(o -> Pair.of(o.getText().string(),o.getScore()))
                                    .findFirst()
                                    .orElse(Pair.of(word.getText().string(),0f))
                    ).collect(Collectors.toMap( Pair::getKey,Pair::getValue)))
            )
            .collect(Collectors.toMap(
                    Pair::getKey,
                    p -> Pair.of(
                            String.join(" ", p.getValue().keySet()),
                            p.getValue().values().stream().mapToDouble(Float::floatValue).sum())));

    return spellcheck.values().stream()
            .filter( v -> v.getValue() > 0.0)
            .sorted((p1,p2) -> Double.compare(p2.getValue(),p1.getValue()))
            .map(Pair::getKey)
            .collect(Collectors.toList());
}
 
Example #3
Source File: Suggest.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(StreamOutput out) throws IOException {
    out.writeText(text);
    out.writeVInt(offset);
    out.writeVInt(length);
    out.writeVInt(options.size());
    for (Option option : options) {
        option.writeTo(out);
    }
}
 
Example #4
Source File: TermSuggestion.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public int compare(Suggestion.Entry.Option first, Suggestion.Entry.Option second) {
    // first criteria: the distance
    int cmp = Float.compare(second.getScore(), first.getScore());
    if (cmp != 0) {
        return cmp;
    }
    return FREQUENCY.compare(first, second);
}
 
Example #5
Source File: Suggest.java    From Elasticsearch with 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;

    Option that = (Option) o;
    return text.equals(that.text);

}
 
Example #6
Source File: TermSuggestion.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected Comparator<Option> sortComparator() {
    switch (sort) {
    case SCORE:
        return SCORE;
    case FREQUENCY:
        return FREQUENCY;
    default:
        throw new ElasticsearchException("Could not resolve comparator for sort key: [" + sort + "]");
    }
}
 
Example #7
Source File: Suggest.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject();
    builder.field(Fields.TEXT, text);
    builder.field(Fields.OFFSET, offset);
    builder.field(Fields.LENGTH, length);
    builder.startArray(Fields.OPTIONS);
    for (Option option : options) {
        option.toXContent(builder, params);
    }
    builder.endArray();
    builder.endObject();
    return builder;
}
 
Example #8
Source File: Suggest.java    From Elasticsearch with 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 #9
Source File: Suggest.java    From Elasticsearch with 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 #10
Source File: SimpleSuggestionBuilder.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public List<? extends Option> getOptions(ElasticsearchTemplate elasticsearchTemplate){
	if(StringUtils.isBlank(text)){
		return Collections.emptyList();
	}
	return get(elasticsearchTemplate, response->{
		Suggestion<?> suggestion = response.getSuggest().getSuggestion(name);
		if(suggestion==null || suggestion.getEntries().isEmpty()){
			return Collections.emptyList();
		}
		Suggestion.Entry<? extends Option> entry = suggestion.getEntries().get(0);
		List<? extends Option> options = entry.getOptions();
		return options;
	});
}
 
Example #11
Source File: TermSuggestion.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
protected void mergeInto(Suggestion.Entry.Option otherOption) {
    super.mergeInto(otherOption);
    freq += ((Option) otherOption).freq;
}
 
Example #12
Source File: Suggest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public Option() {
}
 
Example #13
Source File: TermSuggestion.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
protected Option() {
    super();
}
 
Example #14
Source File: TermSuggestion.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
protected Option(Text text, int freq, float score) {
    super(text, score);
    this.freq = freq;
}
 
Example #15
Source File: TermSuggestion.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
protected Option newOption() {
    return new Option();
}
 
Example #16
Source File: ProductQueryServiceImpl.java    From elasticsearch-tutorial with MIT License 4 votes vote down vote up
@Override
    public List<AutoSuggestionEntry> getAutoSuggestions(ElasticSearchIndexConfig config, String queryString)
    {
        TermSuggestionBuilder suggesBuilder = SuggestBuilder.termSuggestion(SearchFacetName.AUTO_SUGGESTION.getCode())
                                                             .field(SearchDocumentFieldName.KEYWORDS.getFieldName())
                                                             .analyzer(config.getAutoSuggestionAnalyzerName())
                                                             .size(20)
                                                             .text(queryString)
//                                                             .suggestMode("always")
//                                                             .stringDistance("ngram")
                                                             ;
        
//        CompletionSuggestionBuilder suggesBuilder = new CompletionSuggestionBuilder(SearchFacetName.AUTO_SUGGESTION.getCode())
//                .field(SearchDocumentFieldName.KEYWORDS.getFieldName())
//                .analyzer(config.getAutoSuggestionAnalyzerName())
//                .size(20)
//                .text(queryString)
////                .stringDistance("ngram")
//                ;
        
//        PhraseSuggestionBuilder suggesBuilder = SuggestBuilder.phraseSuggestion(SearchFacetName.AUTO_SUGGESTION.getCode())
//                                                              .field(SearchDocumentFieldName.TITLE.getFieldName())
//                                                              .analyzer(config.getAutoSuggestionAnalyzerName())
//                                                              .size(10)
//                                                              .text(queryString)
//                                                              ;
        
        SuggestRequestBuilder addSuggestion = searchClientService.getClient().prepareSuggest(config.getIndexAliasName())
                                        .addSuggestion(suggesBuilder);
        
        try
        {
            logger.debug("Auto Suggestion request is {}", suggesBuilder.toXContent(jsonBuilder().startObject(), null).prettyPrint().string());
        } catch (IOException e)
        {
            //Do nothing  
            logger.error("Error in to string", e);
        }

        SuggestResponse suggestResponse = addSuggestion.get();
        
        logger.debug("Auto Suggestion response is {}", suggestResponse);
        
        List<AutoSuggestionEntry> suggestions = new ArrayList<AutoSuggestionEntry>();

        if(suggestResponse !=null && suggestResponse.getSuggest() !=null && suggestResponse.getSuggest().getSuggestion(SearchFacetName.AUTO_SUGGESTION.getCode()) !=null)
        {
            for (org.elasticsearch.search.suggest.Suggest.Suggestion.Entry<? extends Option> suggestEntry : suggestResponse.getSuggest().getSuggestion(SearchFacetName.AUTO_SUGGESTION.getCode()).getEntries())
            {
                for (Option option : suggestEntry.getOptions())
                {
                    int count = ((TermSuggestion.Entry.Option) option).getFreq();
                    AutoSuggestionEntry autoSuggestionEntry = new AutoSuggestionEntry(option.getText().string(), count);
                    suggestions.add(autoSuggestionEntry);
                }
            }
        }
        
        return suggestions;
    }
 
Example #17
Source File: ProductQueryServiceImpl.java    From searchanalytics-bigdata with MIT License 4 votes vote down vote up
@Override
public List<AutoSuggestionEntry> getAutoSuggestions(
		final ElasticSearchIndexConfig config, final String queryString) {
	final TermSuggestionBuilder suggesBuilder = SuggestBuilder
			.termSuggestion(SearchFacetName.AUTO_SUGGESTION.getCode())
			.field(SearchDocumentFieldName.KEYWORDS.getFieldName())
			.analyzer(config.getAutoSuggestionAnalyzerName()).size(20)
			.text(queryString)
	// .suggestMode("always")
	// .stringDistance("ngram")
	;
	// CompletionSuggestionBuilder suggesBuilder = new
	// CompletionSuggestionBuilder(SearchFacetName.AUTO_SUGGESTION.getCode())
	// .field(SearchDocumentFieldName.KEYWORDS.getFieldName())
	// .analyzer(config.getAutoSuggestionAnalyzerName())
	// .size(20)
	// .text(queryString)
	// // .stringDistance("ngram")
	// ;
	// PhraseSuggestionBuilder suggesBuilder =
	// SuggestBuilder.phraseSuggestion(SearchFacetName.AUTO_SUGGESTION.getCode())
	// .field(SearchDocumentFieldName.TITLE.getFieldName())
	// .analyzer(config.getAutoSuggestionAnalyzerName())
	// .size(10)
	// .text(queryString)
	// ;
	final SuggestRequestBuilder addSuggestion = searchClientService
			.getClient().prepareSuggest(config.getIndexAliasName())
			.addSuggestion(suggesBuilder);
	try {
		logger.debug("Auto Suggestion request is {}", suggesBuilder
				.toXContent(jsonBuilder().startObject(), null)
				.prettyPrint().string());
	} catch (final IOException e) {
		// Do nothing
		logger.error("Error in to string", e);
	}
	final SuggestResponse suggestResponse = addSuggestion.get();
	logger.debug("Auto Suggestion response is {}", suggestResponse);
	final List<AutoSuggestionEntry> suggestions = new ArrayList<AutoSuggestionEntry>();
	if (suggestResponse != null
			&& suggestResponse.getSuggest() != null
			&& suggestResponse.getSuggest().getSuggestion(
					SearchFacetName.AUTO_SUGGESTION.getCode()) != null) {
		for (final org.elasticsearch.search.suggest.Suggest.Suggestion.Entry<? extends Option> suggestEntry : suggestResponse
				.getSuggest()
				.getSuggestion(SearchFacetName.AUTO_SUGGESTION.getCode())
				.getEntries()) {
			for (final Option option : suggestEntry.getOptions()) {
				final int count = ((TermSuggestion.Entry.Option) option)
						.getFreq();
				final AutoSuggestionEntry autoSuggestionEntry = new AutoSuggestionEntry(
						option.getText().string(), count);
				suggestions.add(autoSuggestionEntry);
			}
		}
	}
	return suggestions;
}
 
Example #18
Source File: Suggest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
protected void mergeInto(Option otherOption) {
    score = Math.max(score, otherOption.score);
}
 
Example #19
Source File: Suggest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public Option(Text text, float score) {
    this(text, null, score);
}
 
Example #20
Source File: Suggest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public Option(Text text, Text highlighted, float score) {
    this(text, highlighted, score, null);
}
 
Example #21
Source File: Suggest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public Option(Text text, Text highlighted, float score, Boolean collateMatch) {
    this.text = text;
    this.highlighted = highlighted;
    this.score = score;
    this.collateMatch = collateMatch;
}
 
Example #22
Source File: Suggest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
protected O newOption(){
    return (O) new Option();
}
 
Example #23
Source File: Suggest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
protected Comparator<Option> sortComparator() {
    return COMPARATOR;
}
 
Example #24
Source File: Suggest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public Iterator<Suggestion<? extends Entry<? extends Option>>> iterator() {
    return suggestions.iterator();
}
 
Example #25
Source File: Suggest.java    From Elasticsearch with 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 #26
Source File: Suggest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public Suggest(List<Suggestion<? extends Entry<? extends Option>>> suggestions) {
    this(null, suggestions);
}