1 # ====================================================================
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at
6 # http://www.apache.org/licenses/LICENSE-2.0
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13 # ====================================================================
16 from lucene import SortField, Term, IndexReader, FieldCache, \
17 PythonFieldComparatorSource, PythonFieldComparator, Double
20 # A FieldComparatorSource implementation
23 class DistanceComparatorSource(PythonFieldComparatorSource):
25 def __init__(self, x, y):
26 super(DistanceComparatorSource, self).__init__()
31 def newComparator(self, fieldName, numHits, sortPos, reversed):
33 class DistanceScoreDocLookupComparator(PythonFieldComparator):
35 def __init__(_self, fieldName, numHits):
36 super(DistanceScoreDocLookupComparator, _self).__init__()
37 _self.values = [0.0] * numHits
38 _self.fieldName = fieldName
40 def setNextReader(_self, reader, docBase):
42 _self.xDoc = FieldCache.DEFAULT.getInts(reader, "x")
43 _self.yDoc = FieldCache.DEFAULT.getInts(reader, "y")
45 def _getDistance(_self, doc):
47 deltax = _self.xDoc[doc] - self.x
48 deltay = _self.yDoc[doc] - self.y
50 return sqrt(deltax * deltax + deltay * deltay)
52 def compare(_self, slot1, slot2):
54 if _self.values[slot1] < _self.values[slot2]:
56 if _self.values[slot1] > _self.values[slot2]:
61 def setBottom(_self, slot):
63 _self._bottom = _self.values[slot]
65 def compareBottom(_self, doc):
67 docDistance = _self._getDistance(doc)
68 if _self._bottom < docDistance:
70 if _self._bottom > docDistance:
75 def copy(_self, slot, doc):
77 _self.values[slot] = _self._getDistance(doc)
79 def value(_self, slot):
81 return Double(_self.values[slot])
84 return SortField.CUSTOM
86 return DistanceScoreDocLookupComparator(fieldName, numHits)
90 return "Distance from (" + self.x + "," + self.y + ")"