Search code examples
marklogic

How to search on numbers in the same way like searching on strings


In my code I have this query

cts.elementWordQuery(["name"], "ca*", ["wildcarded])

and I want to make similar query on orher field but the field type is a number.

tldr want to method:

cts.elementWordQuery(["number-field"], "909*", ["wildcarded])

return documents with number-field property equal 9091, 9091231 etc.


Solution

  • I'm assuming this is a JSON document, and it's a numeric property?

    You could create a field range index as string, and then:

    Use cts.fieldValueMatch() with a wildcard to find values that start with 909, convert those strings to Number and then use cts.fieldValueQuery() to look for those numbers:

    const values = [];
    for (const str of cts.fieldValueMatch('number-field', "909*")) { 
      values.push(Number(str)) 
    }
    cts.search(cts.fieldValueQuery('number-field', values))
    

    Or use cts.fieldValueMatch() to fetch the values starting with 909* and use them as value criteria for equality in cts.fieldRangeQuery():

    cts.search(cts.fieldRangeQuery('number-field', '=', cts.fieldValueMatch('number-field', '909*')));
    

    Or use cts.fieldRangeQuery (might also need to add a < constraint):

    cts.fieldRangeQuery('number-field', ">", "909")