Hello.
I would like to sort user_id stored as a string as a number in a full text search.
My data is as follows.
I want to sort user_id as 1,2,11,101, but in the current query it is 1,101,11,2.
Is there any way to implement this without storing the user_id as a number?
I tried “sort”: [“+TO_NUMBER(user_id)”] but it doesn’t work.
@ryosek unfortunately text ordering is lexicographic. So a search index will only order your examples as 1, 101, 11, 2.
N1QL’s text sorting is also lexicographic but it supports the to_number function when used within the ORDER BY clause. You cannot embed a N1QL function within the SEARCH function though.
So your query will simply need to change to this to get things to work your way -
SELECT search_score() AS _score, *
FROM test._default.record USE INDEX (USING FTS)
WHERE SEARCH(test,{ "fields": ["*"], "highlight": {}, "size": 100, "from" : 0, "query": { "query": "new york"}},{ "index":"Record" })
ORDER BY to_number(user_id)
@abhinav
Thank you, I tried your query and the results are ordered as numbers!
But does this query work with limit clause?
For example, if user_id is “1”, “101”, “11”, “2” and I run the query with { “size” : 3, “from” : 0, } and ORDER BY to_number(user_id) in the query, which would be the correct result?
You must remove size, from in search and the following should give right results.
As you are doing order by out side you don’t want apply size/from inside the SERACH(). Let all qualified results produced then order and limit.
SELECT search_score() AS _score, *
FROM test._default.record USE INDEX (USING FTS)
WHERE SEARCH(test,{ "fields": ["*"], "highlight": {}, "query": { "query": "new york"}},{ "index":"Record" })
ORDER BY to_number(user_id)
OFFSET 10
LIMIT 100;