user3169643
user3169643

Reputation: 41

elasticsearch upon multiple fields

I want to search a keyword in a document which has couple of fields. the search should occur on two fields only : id and name.

I need to write a query which has this property: If your search input(keyword) is numeric, and it happens that there are two different records which contain this keyword in id field and name field, the one with the id field should be shown first(it doesn't have to be a perfect match in the ID field).

for example, if i have these two records: 1. id: 5 name:"kuku" 2. id: 10 name: "kuku523"

and i look for "5" as keyword, i should get higher score for the first record(in the hits list).

The "id" field is numeric, and the "name" field is a string.

I've been trying to use the matchQuery, multiMatchQuery and fuzzyLikeThis.

The multiMatchQuery gives higher score to the second record instead of the first one, which looks really odd to me(because there is a "perfect match" on the first record).

setQuery(QueryBuilders.multiMatchQuery(searchParam, ID, NAME));

and the fuzzyLike This throws an exception about the numeric field.

setQuery(QueryBuilders.fuzzyLikeThisQuery(ID,NAME).likeText(searchParam))

the tremQuery doesn't really gives a solution.

What query i should use in a case like this?

Upvotes: 1

Views: 66

Answers (1)

Rahul
Rahul

Reputation: 16335

You need to make id a String field as full-text-searches do not work on numeric fields.

OR

If you still need id field to be numeric for term queries, you can use multifields Create a multi-field, that will contain a number field and also a string for searching

PUT /test/items/_mapping
{
  "items" : {
    "properties" : {
      "id" : {
          "fields" : {
            "numeric" : {
              "type" : "integer",
              "index" : "not_analyzed"
            },
            "text" : {
              "type" : "string",
              "index" : "analyzed"
            }
          }
        }
      }
    }
}

Now, you can use id.numeric for numeric query and id.text for text queries

Upvotes: 1

Related Questions