0

I want to make an autocomplete with elasticsearch

I have tried

however all of them doesn't meet my expectation

suppose I have data like:

PHP Programing
php prado framework
OOP PHP Programming
PHPMyAdmin
PHP
Php

whenever I query PHP, the result will be like above list ^
How to make PHP show first? instead of last
and how come PHP Programming has higher weight than PHP which is the equal to the query?

note: I already added lowercase filter so the query is treated as case-sensitive, which is why both php, Php, PHP match the query

user2033624
  • 21
  • 2
  • 3

2 Answers2

0

I don't know exactly what you are doing, so contributing with some more information would help.

But I get the following to work, not a suggestion example, but it's showing how you can use score to sort

@Test
public void es() throws Exception {
    insert("value", "foo foo");
    insert("value", "foo");
    insert("value", "fooa");
    insert("value", "fao");
    insert("value", "foo potato foo bar");
    insert("value", "foo potato bar");
    insert("value", "foo potato");
    insert("value", "foo vegetable");
    insert("value", "foo vegetable");

    Thread.sleep(1000);
    SearchResponse searchResponse =
        getClient().prepareSearch()
            .setQuery(QueryBuilders.matchPhraseQuery("value", "foo"))
            .addSort(SortBuilders.scoreSort()
                .order(SortOrder.DESC))
            .execute().actionGet();

    Arrays.stream(searchResponse.getHits().getHits())
        .forEach(h -> System.out.println(h.getSource().get("value") + ": " + h.getScore()));
}

Output:

foo: 1.1177831
foo foo: 0.98798996
foo potato foo bar: 0.790392
foo potato: 0.6986144
foo vegetable: 0.6986144
foo vegetable: 0.6986144
foo potato bar: 0.55889153
J2B
  • 1,703
  • 2
  • 16
  • 31
0

To achieve the desired behavior you need to use edgengrams(https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-edgengram-tokenizer.html) on a field which is using edgengram analyzer. To rank exact matches on top of any other prefix matches maintain an additional field which is not analyzed and use it in a should clause to increase its relevance(https://www.elastic.co/guide/en/elasticsearch/guide/current/query-scoring.html)

moyukh bera
  • 124
  • 6