Returns the original query if it was already a positive query, otherwise return the negative of the query (i.e., a positive query). Example: both id:10 and id:-10 will return id:10 The caller can tell the sign of the original by a reference comparison between the original and returned query.
(Query q)
| 139 | * @return Absolute version of the Query |
| 140 | */ |
| 141 | public static Query getAbs(Query q) { |
| 142 | if (q instanceof BoostQuery bq) { |
| 143 | Query subQ = bq.getQuery(); |
| 144 | Query absSubQ = getAbs(subQ); |
| 145 | if (absSubQ.equals(subQ)) return q; |
| 146 | return new BoostQuery(absSubQ, bq.getBoost()); |
| 147 | } |
| 148 | |
| 149 | if (q instanceof WrappedQuery) { |
| 150 | Query subQ = ((WrappedQuery) q).getWrappedQuery(); |
| 151 | Query absSubQ = getAbs(subQ); |
| 152 | if (absSubQ.equals(subQ)) return q; |
| 153 | return new WrappedQuery(absSubQ); |
| 154 | } |
| 155 | |
| 156 | if (!(q instanceof BooleanQuery bq)) return q; |
| 157 | |
| 158 | Collection<BooleanClause> clauses = bq.clauses(); |
| 159 | if (clauses.size() == 0) return q; |
| 160 | |
| 161 | for (BooleanClause clause : clauses) { |
| 162 | if (!clause.isProhibited()) return q; |
| 163 | } |
| 164 | |
| 165 | if (clauses.size() == 1) { |
| 166 | // if only one clause, dispense with the wrapping BooleanQuery |
| 167 | Query negClause = clauses.iterator().next().query(); |
| 168 | // we shouldn't need to worry about adjusting the boosts since the negative |
| 169 | // clause would have never been selected in a positive query, and hence would |
| 170 | // not contribute to a score. |
| 171 | return negClause; |
| 172 | } else { |
| 173 | BooleanQuery.Builder newBqB = new BooleanQuery.Builder(); |
| 174 | // ignore minNrShouldMatch... it doesn't make sense for a negative query |
| 175 | |
| 176 | // the inverse of -a -b is a OR b |
| 177 | for (BooleanClause clause : clauses) { |
| 178 | newBqB.add(clause.query(), BooleanClause.Occur.SHOULD); |
| 179 | } |
| 180 | return newBqB.build(); |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | /** Makes negative queries suitable for querying by lucene. */ |
| 185 | public static Query makeQueryable(Query q) { |