Posted on 25/09/2025 11:36:48
I am not sure it is possible because of the way Lucene works.
Here is the words of my friend:
In Lucene (and Lucene.NET), you cannot directly compare the values of two fields within the query syntax. Lucene’s query parser and search execution are designed around field–value comparisons against a constant (like fieldX:123) or a range (fieldX:[100 TO 200]), not field-to-field comparisons.
Why this limitation exists
-
Lucene’s core data model is inverted index–based. Queries operate on terms mapped to documents, not row-style expressions where one column can be compared to another.
-
At query time, Lucene doesn’t natively join or compare across multiple fields in a single document.
Workarounds
If you need to compare field values, you have a few approaches:
-
Index-time denormalization
Precompute a comparison field. For example, when indexing, you could store fieldA - fieldB or a flag like fieldA_equals_fieldB. Then you query that derived field.
-
Function queries / FunctionScoreQuery
In Lucene 4.x (and Lucene.NET 4.8, which tracks that version), you can use ValueSource-based queries (like FunctionQuery or FunctionScoreQuery).
Example:
var source = new org.apache.lucene.queries.function.valuesource.DualFloatFunction(
new IntFieldSource("fieldA"),
new IntFieldSource("fieldB"),
(a, b) => a - b
);
var functionQuery = new FunctionQuery(source);
You can then filter on this (e.g., only docs where fieldA == fieldB or fieldA > fieldB), but it’s more like a scoring hack. Filtering requires wrapping with Filter logic.
-
Post-processing
Run a broader Lucene query (say, match all documents with constraints on one field) and then in your application code filter the results where fieldA == fieldB.
-
Use an external system (like SQL or Elasticsearch)
If your use case often requires field-to-field comparisons, Lucene may not be the right tool. Elasticsearch (built on Lucene) supports limited field-to-field scripts using painless scripting.
✅ Short answer: No, Lucene.NET 4.x does not support fieldA:fieldB style queries out of the box. You’ll need to either:
-
denormalize at index time,
-
use FunctionQuery/ValueSource for custom comparison, or
-
filter in application logic after retrieval.