3

I've inherited some code which uses the Lucene API to query a Solr index.

The code does a lot of searches, and at the end converts all found lucene documents to solr documents:

// doc:Document

val sdoc = new SolrDocument

for (f:Fieldable <- doc.getFields if f.isStored) {
  sdoc.addField(f.name(),f.stringValue())
}

This works fine, except for when the field value isn't a string, e.g. floats or booleans. On float fields, stringValue() returns some weird characters (e.g. ¿£൱), presumably the string representation of a float.

How do I properly get the float value from a Lucene document?

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Tom Lokhorst
  • 13,658
  • 5
  • 55
  • 71
  • how are you storing floats? which version of lucene are you using? Do you see the correct value when inspected using Luke? – naresh Jan 19 '12 at 10:56

1 Answers1

3

For Numeric stored as binary value, you need to get by doc.getBinaryValue(fieldName) you will get byte[] as return value which you will have to convert it into your appropriate numeric value. This is what you could do:

if(!field.isBinary()){
    sdoc.addField(fieldName, doc.get(fieldName));
} else{
    ByteBuffer buff = ByteBuffer.wrap(doc.getBinaryValue(fieldName));
    sdoc.addField(fieldName, buff.getFloat());
}

Here's a SO Quetion that provides help with the conversion.

Community
  • 1
  • 1
mailboat
  • 1,077
  • 9
  • 17
  • 1
    what if the field is a sdouble (SortableDouble)? the code runs to the not a binary field block for sdouble, as a result, i got a weird string like " @#sV7&"...thanks for your help! – trillions Jun 21 '12 at 18:36
  • NumberUtils.SortableStr2doubleStr(indexedForm); – Yolofy Dec 03 '20 at 14:21