aboutsummaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/search/query/rewrite/RewriterUtils.java
blob: 91c556d0115eb5b78ff49bc0e88c54c7eb7f9c4e (plain) (blame)
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.query.rewrite;

import com.yahoo.fsa.FSA;
import java.util.logging.Level;
import com.yahoo.search.Query;
import com.yahoo.search.intent.model.IntentModel;
import com.yahoo.search.intent.model.InterpretationNode;
import com.yahoo.text.interpretation.Annotations;
import com.yahoo.text.interpretation.Modification;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Logger;

import static com.yahoo.language.LinguisticsCase.toLowerCase;

/**
 * Contains common utilities used by rewriters
 *
 * @author Karen Sze Wing Lee
 */
public class RewriterUtils {

    private static final Logger utilsLogger = Logger.getLogger(RewriterUtils.class.getName());

    // Tracelevel for debug log of this rewriter
    private static final int TRACELEVEL = 3;

    /**
     * Load FSA from file
     *
     * @param file FSA dictionary file object
     * @param query Query object from the searcher, could be null if not available
     * @return FSA The FSA object for the input file path
     */
    public static FSA loadFSA(File file, Query query) throws IOException {
        log(utilsLogger, query, "Loading FSA file");
        String filePath = null;

        try {
            filePath = file.getAbsolutePath();
        } catch (SecurityException e1) {
            error(utilsLogger, query, "No read access for the FSA file");
            throw new IOException("No read access for the FSA file");
        }

        FSA fsa = loadFSA(filePath, query);

        return fsa;
    }

    /**
     * Load FSA from file
     *
     * @param filename FSA dictionary file path
     * @param query Query object from the searcher, could be null if not available
     * @return FSA The FSA object for the input file path
     */
    public static FSA loadFSA(String filename, Query query) throws IOException {
        log(utilsLogger, query, "Loading FSA file from: " + filename);

        if(!new File(filename).exists()) {
            error(utilsLogger, query, "File does not exist : " + filename);
            throw new IOException("File does not exist : " + filename);
        }

        FSA fsa;
        try {
            fsa = new FSA(filename);
        } catch (RuntimeException e) {
            error(utilsLogger, query, "Invalid FSA file");
            throw new IOException("Invalid FSA file");
        }

        if (!fsa.isOk()) {
            error(utilsLogger, query, "Unable to load FSA file from : " + filename);
            throw new IOException("Not able to load FSA file from : " + filename);
        }
        log(utilsLogger, query, "Loaded FSA successfully from file : " + filename);
        return fsa;
    }

    /**
     * Retrieve rewrite from FSA given the original query
     *
     * @param query Query object from searcher
     * @param dictName FSA dictionary name
     * @param rewriterDicts list of rewriter dictionaries
     *                      It has the following format:
     *                      HashMap<dictionary name, FSA>
     * @param key The original query used to retrieve rewrite
     *            from the dictionary
     * @return String The retrieved rewrites, null if query
     *         doesn't exist
     */
    public static String getRewriteFromFSA(Query query,
                                           HashMap<String, Object> rewriterDicts,
                                           String dictName,
                                           String key) throws RuntimeException {
        if(rewriterDicts==null) {
            error(utilsLogger, query, "HashMap containing rewriter dicts is null");
            throw new RuntimeException("HashMap containing rewriter dicts is null");
        }

        FSA fsa = (FSA)rewriterDicts.get(dictName);

        if(fsa==null) {
            error(utilsLogger, query, "Error retrieving FSA dictionary: " + dictName);
            throw new RuntimeException("Error retrieving FSA dictionary: " + dictName);
        }

        String result = null;
        result = fsa.lookup(key);
        log(utilsLogger, query, "Retrieved rewrite: " + result);

        return result;
    }

    /**
     * Get config parameter value set in query profile
     *
     * @param query Query object from the searcher
     * @param rewriterName Name of the rewriter
     * @param paramName parameter to be retrieved
     * @return parameter value or null if not found
     */
    public static String getQPConfig(Query query,
                                     String rewriterName,
                                     String paramName) {
        log(utilsLogger, query, "Retrieving config parameter value of: " +
            rewriterName + "." + paramName);

        return getUserParam(query, rewriterName + "." + paramName);
    }

    /**
     * Get rewriter chain value
     *
     * @param query Query object from the searcher
     * @return parameter value or null if not found
     */
    public static String getRewriterChain(Query query) {
        log(utilsLogger, query, "Retrieving rewriter chain value: " +
            RewriterConstants.REWRITER_CHAIN);

        return getUserParam(query, RewriterConstants.REWRITER_CHAIN);
    }

    /**
     * Get user param value
     *
     * @param query Query object from the searcher
     * @param paramName parameter to be retrieved
     * @return parameter value or null if not found
     */
    public static String getUserParam(Query query, String paramName) {
        log(utilsLogger, query, "Retrieving user param value: " + paramName);

        if (paramName == null) {
            error(utilsLogger, query, "Parameter name is null");
            return null;
        }

        String paramValue = null;
        paramValue = query.properties().getString(paramName);
        log(utilsLogger, query, "Param value retrieved is: " + paramValue);

        return paramValue;
    }

    /**
     * Retrieve metadata passed by previous rewriter from query properties
     * Initialize values if this is the first rewriter
     *
     * @param query Query object from the searcher
     * @return hashmap containing the metadata
     */
    public static HashMap<String, Object> getRewriteMeta(Query query) {
       log(utilsLogger, query, "Retrieving metadata passed by previous rewriter");

        @SuppressWarnings("unchecked")
        HashMap<String, Object> rewriteMeta =
                (HashMap<String, Object>)query.properties().get(RewriterConstants.REWRITE_META);

       if (rewriteMeta == null) {
           log(utilsLogger, query, "No metadata available from previous rewriter");
           rewriteMeta = new HashMap<>();
           rewriteMeta.put(RewriterConstants.REWRITTEN, false);
           rewriteMeta.put(RewriterConstants.DICT_KEY, getNormalizedOriginalQuery(query));
       } else {
           if((Boolean)rewriteMeta.get(RewriterConstants.REWRITTEN)) {
               log(utilsLogger, query, "Query has been rewritten by previous rewriters");
           } else {
               log(utilsLogger, query, "Query has not been rewritten by previous rewriters");
           }
           log(utilsLogger, query, "Dict key passed by previous rewriter: " +
                                   rewriteMeta.get(RewriterConstants.DICT_KEY));
       }

       return rewriteMeta;
    }

    /**
     * Pass metadata to the next rewriter through query properties
     *
     * @param query Query object from the searcher
     * @param metadata HashMap containing the metadata
     */
    public static void setRewriteMeta(Query query, HashMap<String, Object> metadata) {
        log(utilsLogger, query, "Passing metadata to the next rewriter");

        query.properties().set(RewriterConstants.REWRITE_META, metadata);
        log(utilsLogger, query, "Successfully passed metadata to the next rewriter");
    }


    /**
     * Retrieve spell corrected query with highest score from QLAS
     *
     * @param query Query object from the searcher
     * @param qss_rw Whether to consider qss_rw modification
     * @param qss_sugg Whether ot consider qss_sugg modification
     * @return Spell corrected query or null if not found
     */
    public static String getSpellCorrected(Query query,
                                           boolean qss_rw,
                                           boolean qss_sugg)
                                           throws RuntimeException {
        log(utilsLogger, query, "Retrieving spell corrected query");

        // Retrieve Intent Model
        IntentModel intentModel = IntentModel.getFrom(query);
        if(intentModel==null) {
            error(utilsLogger, query, "Unable to retrieve intent model");
            throw new RuntimeException("Not able to retrieve intent model");
        }

        double max_score = 0;
        String spellCorrected = null;

        // Iterate through all interpretations to get a spell corrected
        // query with highest score
        for (InterpretationNode interpretationNode : intentModel.children()) {
            Modification modification = interpretationNode.getInterpretation()
                                                          .getModification();
            Annotations annotations = modification.getAnnotation();
            Double score = annotations.getDouble("score");

            // Check if it's higher than the max score
            if(score!=null && score>max_score) {
                Boolean isQSSRewrite = annotations.getBoolean("qss_rw");
                Boolean isQSSSuggest = annotations.getBoolean("qss_sugg");

                // Check if it's qss_rw or qss_sugg
                if((qss_rw && isQSSRewrite!=null && isQSSRewrite) ||
                   (qss_sugg && isQSSSuggest!=null && isQSSSuggest)) {
                    max_score = score;
                    spellCorrected = modification.getText();
                }
            }
        }

        if(spellCorrected!=null) {
            log(utilsLogger, query, "Successfully retrieved spell corrected query: " +
                spellCorrected);
        } else {
            log(utilsLogger, query, "No spell corrected query is retrieved");
        }

        return spellCorrected;
    }

    /**
     * Retrieve normalized original query from query object
     *
     * @param query Query object from searcher
     * @return normalized query
     */
    public static String getNormalizedOriginalQuery(Query query) {
        return toLowerCase(query.getModel().getQueryString()).trim();
    }

    /**
     * Log message
     *
     * @param logger Logger used for this msg
     * @param msg Log message
     */
    public static void log(Logger logger, String msg) {
        logger.log(Level.FINE, () -> logger.getName() + ": " + msg);
    }

    /**
     * Log message
     *
     * @param logger Logger used for this msg
     * @param query Query object from searcher
     * @param msg Log message
     */
    public static void log(Logger logger, Query query, String msg) {
        if(query!=null) {
            query.trace(logger.getName() + ": " + msg, true, TRACELEVEL);
        }
        logger.log(Level.FINE, () -> logger.getName() + ": " + msg);
    }

    /**
     * Print error message
     *
     * @param logger Logger used for this msg
     * @param msg Error message
     */
    public static void error(Logger logger, String msg) {
        logger.severe(logger.getName() + ": " + msg);
    }

    /**
     * Print error message
     *
     * @param logger Logger used for this msg
     * @param query Query object from searcher
     * @param msg Error message
     */
    public static void error(Logger logger, Query query, String msg) {
        if (query != null)
            query.trace(logger.getName() + ": " + msg, true, TRACELEVEL);
        logger.severe(logger.getName() + ": " + msg);
    }

}