Lucene Multi Term Query field search working example in Scala

It was unnecessarily difficult to figure out how to generate a simple query for Lucene able to search documents based on multiple fields.

The way I have personally come to do this is to generate the String query itself and then parse it into a query object.

Here we go (Scala code)

val searchInput = Map(“First Name” -> “John”, “Last Name” -> “Do”)

val parser = new MultiFieldQueryParser(searchInput.keySet.toArray, new CaseInsensitiveWhitespaceAnalyzer())

parser.setDefaultOperator(QueryParserBase.AND_OPERATOR)

val queryString = searchInput.map(i => “(“ + i._1.replaceAll(“ “, “\\\\ “) + “:” + i._2 + “*)”).mkString(“ “)

val query = parser.parse(queryString)

And that is that.

Perhaps obvious? I have wasted enough time trying to find a working example of a multi-field query that I felt it is worthy to note it down.

Let me know of a more elegant approach, I am sure it can be rewritten in a builder pattern, but for the life of me I did not find an example to quickly solve this.

Full-stack software engineer — “The computer programmer is a creator of universes” ~ Joseph Weizenbaum

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store