summaryrefslogtreecommitdiff
path: root/core/src/main/java/org/elasticsearch/common/lucene/search/function/FieldValueFactorFunction.java
blob: 3bc5542c2aa13b7666c0d17460bd2a9f7c6f2940 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.elasticsearch.common.lucene.search.function;

import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.search.Explanation;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.index.fielddata.FieldData;
import org.elasticsearch.index.fielddata.IndexNumericFieldData;
import org.elasticsearch.index.fielddata.SortedNumericDoubleValues;

import java.io.IOException;
import java.util.Locale;
import java.util.Objects;

/**
 * A function_score function that multiplies the score with the value of a
 * field from the document, optionally multiplying the field by a factor first,
 * and applying a modification (log, ln, sqrt, square, etc) afterwards.
 */
public class FieldValueFactorFunction extends ScoreFunction {
    private final String field;
    private final float boostFactor;
    private final Modifier modifier;
    /**
     * Value used if the document is missing the field.
     */
    private final Double missing;
    private final IndexNumericFieldData indexFieldData;

    public FieldValueFactorFunction(String field, float boostFactor, Modifier modifierType, Double missing,
            IndexNumericFieldData indexFieldData) {
        super(CombineFunction.MULTIPLY);
        this.field = field;
        this.boostFactor = boostFactor;
        this.modifier = modifierType;
        this.indexFieldData = indexFieldData;
        this.missing = missing;
    }

    @Override
    public LeafScoreFunction getLeafScoreFunction(LeafReaderContext ctx) {
        final SortedNumericDoubleValues values;
        if(indexFieldData == null) {
            values = FieldData.emptySortedNumericDoubles(ctx.reader().maxDoc());
        } else {
            values = this.indexFieldData.load(ctx).getDoubleValues();
        }

        return new LeafScoreFunction() {

            @Override
            public double score(int docId, float subQueryScore) {
                values.setDocument(docId);
                final int numValues = values.count();
                double value;
                if (numValues > 0) {
                    value = values.valueAt(0);
                } else if (missing != null) {
                    value = missing;
                } else {
                    throw new ElasticsearchException("Missing value for field [" + field + "]");
                }
                double val = value * boostFactor;
                double result = modifier.apply(val);
                if (Double.isNaN(result) || Double.isInfinite(result)) {
                    throw new ElasticsearchException("Result of field modification [" + modifier.toString() + "(" + val
                            + ")] must be a number");
                }
                return result;
            }

            @Override
            public Explanation explainScore(int docId, Explanation subQueryScore) {
                String modifierStr = modifier != null ? modifier.toString() : "";
                String defaultStr = missing != null ? "?:" + missing : "";
                double score = score(docId, subQueryScore.getValue());
                return Explanation.match(
                        CombineFunction.toFloat(score),
                        String.format(Locale.ROOT,
                                "field value function: %s(doc['%s'].value%s * factor=%s)", modifierStr, field, defaultStr, boostFactor));
            }
        };
    }

    @Override
    public boolean needsScores() {
        return false;
    }

    @Override
    protected boolean doEquals(ScoreFunction other) {
        FieldValueFactorFunction fieldValueFactorFunction = (FieldValueFactorFunction) other;
        return this.boostFactor == fieldValueFactorFunction.boostFactor &&
                Objects.equals(this.field, fieldValueFactorFunction.field) &&
                Objects.equals(this.modifier, fieldValueFactorFunction.modifier);
    }

    @Override
    protected int doHashCode() {
        return Objects.hash(boostFactor, field, modifier);
    }

    /**
     * The Type class encapsulates the modification types that can be applied
     * to the score/value product.
     */
    public enum Modifier implements Writeable {
        NONE {
            @Override
            public double apply(double n) {
                return n;
            }
        },
        LOG {
            @Override
            public double apply(double n) {
                return Math.log10(n);
            }
        },
        LOG1P {
            @Override
            public double apply(double n) {
                return Math.log10(n + 1);
            }
        },
        LOG2P {
            @Override
            public double apply(double n) {
                return Math.log10(n + 2);
            }
        },
        LN {
            @Override
            public double apply(double n) {
                return Math.log(n);
            }
        },
        LN1P {
            @Override
            public double apply(double n) {
                return Math.log1p(n);
            }
        },
        LN2P {
            @Override
            public double apply(double n) {
                return Math.log1p(n + 1);
            }
        },
        SQUARE {
            @Override
            public double apply(double n) {
                return Math.pow(n, 2);
            }
        },
        SQRT {
            @Override
            public double apply(double n) {
                return Math.sqrt(n);
            }
        },
        RECIPROCAL {
            @Override
            public double apply(double n) {
                return 1.0 / n;
            }
        };

        public abstract double apply(double n);

        @Override
        public void writeTo(StreamOutput out) throws IOException {
            out.writeVInt(this.ordinal());
        }

        public static Modifier readFromStream(StreamInput in) throws IOException {
            int ordinal = in.readVInt();
            if (ordinal < 0 || ordinal >= values().length) {
                throw new IOException("Unknown Modifier ordinal [" + ordinal + "]");
            }
            return values()[ordinal];
        }

        @Override
        public String toString() {
            return super.toString().toLowerCase(Locale.ROOT);
        }

        public static Modifier fromString(String modifier) {
            return valueOf(modifier.toUpperCase(Locale.ROOT));
        }
    }
}