aboutsummaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/prelude/query/NearItem.java
blob: 3a2b6c974bf11a0c19743bcf21d6817c428b5b3e (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query;

import com.yahoo.compress.IntegerCompressor;
import com.yahoo.prelude.query.textualrepresentation.Discloser;

import java.nio.ByteBuffer;
import java.util.Objects;


/**
 * A set of terms which must be near each other to match.
 *
 * @author bratseth
 * @author havardpe
 */
public class NearItem extends CompositeItem {

    protected int distance;

    /** The default distance used if none is specified: 2 */
    public static final int defaultDistance = 2;

    /** Creates a NEAR item with distance 2 */
    public NearItem() {
        setDistance(defaultDistance);
    }

    /**
     * Creates a <i>near</i> item with a limit to the distance between the words.
     *
     * @param distance the maximum position difference between the words which should be counted as a match
     */
    public NearItem(int distance) {
        setDistance(distance);
    }

    public void setDistance(int distance) {
        if (distance < 0)
            throw new IllegalArgumentException("Can not use negative distance " + distance);
        this.distance = distance;
    }

    public int getDistance() {
        return distance;
    }

    @Override
    public ItemType getItemType() {
        return ItemType.NEAR;
    }

    @Override
    public String getName() {
        return "NEAR";
    }

    @Override
    protected void encodeThis(ByteBuffer buffer) {
        super.encodeThis(buffer);
        IntegerCompressor.putCompressedPositiveNumber(distance, buffer);
    }

    @Override
    public void disclose(Discloser discloser) {
        super.disclose(discloser);
        discloser.addProperty("limit", distance);
    }

    /** Appends the heading of this string - <code>[getName()]([limit]) </code> */
    @Override
    protected void appendHeadingString(StringBuilder buffer) {
        buffer.append(getName());
        buffer.append("(");
        buffer.append(distance);
        buffer.append(")");
        buffer.append(" ");
    }

    @Override
    public boolean equals(Object object) {
        if (!super.equals(object)) return false;
        NearItem other = (NearItem) object; // Ensured by superclass
        if (this.distance != other.distance) return false;
        return true;
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), distance);
    }

}