summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/Elastic/QueryEngine/SortBuilder.php
blob: 6d01796e2158f72abb71147e401d2f8effec8acb (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
<?php

namespace SMW\Elastic\QueryEngine;

use Psr\Log\LoggerAwareTrait;
use SMW\DataTypeRegistry;
use SMW\DIProperty;
use SMW\Store;
use SMWQuery as Query;

/**
 * @license GNU GPL v2+
 * @since 3.0
 *
 * @author mwjames
 */
class SortBuilder {

	use LoggerAwareTrait;

	/**
	 * @var Store
	 */
	private $store;

	/**
	 * @var FieldMapper
	 */
	private $fieldMapper;

	/**
	 * @var string
	 */
	private $scoreField;

	/**
	 * @var boolean
	 */
	private $isScoreSort = false;

	/**
	 * @since 3.0
	 *
	 * @param Store $store
	 */
	public function __construct( Store $store ) {
		$this->store = $store;
		$this->fieldMapper = new FieldMapper();
	}

	/**
	 * @since 3.0
	 *
	 * @param string $scoreField
	 */
	public function setScoreField( $scoreField ) {
		$this->scoreField = $scoreField;
	}

	/**
	 * @since 3.0
	 *
	 * @return boolean
	 */
	public function isScoreSort() {
		return $this->isScoreSort;
	}

	/**
	 * @since 3.0
	 *
	 * @param Query $query
	 *
	 * @return array
	 */
	public function makeSortField( Query $query ) {

		// @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html#_memory_considerations
		// "... the relevant sorted field values are loaded into memory. This means
		// that per shard, there should be enough memory ... string based types,
		// the field sorted on should not be analyzed / tokenized ... numeric
		// types it is recommended to explicitly set the type to narrower types"

		$this->isScoreSort = $query->getOption( Query::SCORE_SORT );

		if ( $query->getOption( Query::SCORE_SORT ) ) {
			return [ [ '_score' => [ 'order' => $query->getOption( Query::SCORE_SORT ) ] ], [], false, false];
		}

		return $this->getFields( $query->getSortKeys() );
	}

	private function getFields( array $sortKeys ) {

		$isRandom = false;
		$isConstantScore = true;
		$sort = [];
		$sortFields = [];
		$sortKeysCount = count( $sortKeys );

		foreach ( $sortKeys as $key => $order ) {
			$order = strtolower( $order );
			$isRandom = strpos( $order, 'rand' ) !== false;

			if ( strtolower( $key ) === $this->scoreField ) {
				$key = '_score';
				$this->isScoreSort = true;
				$isConstantScore = false;
			}

			if ( $key === '' || $key === '#' ) {
				$this->addDefaultField( $sort, $order, $sortKeysCount );
			} else {
				$this->addField( $sort, $sortFields, $key, $order );
			}
		}

		return [ $sort, $sortFields, $isRandom, $isConstantScore ];
	}

	private function addDefaultField( &$sort, $order, $sortKeysCount ) {
		$sort['subject.sortkey.sort'] = [ 'order' => $order ];

		// Add title as extra criteria in case an entity uses the same sortkey
		// to clarify its relative position, @see T:P0416#8
		// Only add the title as determining factor when no other sort parameter
		// is available
		if ( $sortKeysCount == 1 ) {
			$sort['subject.title.sort'] = [ 'order' => $order ];
		}
	}

	private function addField( &$sort, &$sortFields, $key, $order ) {

		$dataTypeRegistry = DataTypeRegistry::getInstance();
		$chain = false;

		// Chain?
		if ( strpos( $key, '.' ) !== false ) {
			$list = explode( '.', $key );
			$last = current( $list );
		} else {
			$list = [ $key ];
		}

		foreach ( $list as $key ) {

			if ( $key === '_score' ) {
				$field = '_score';
			} else {
				$property = DIProperty::newFromUserLabel( $key );

				$field = $this->fieldMapper->getField( $property, 'Field' );

				$pid = $this->fieldMapper->getPID(
					$this->store->getObjectIds()->getSMWPropertyID( $property )
				);

				// Only record the last key to be used as possible existential
				// enforcement
				if ( $chain === false ) {
					$sortFields[] = "$pid.$field";
				}

				// Use special sort field on mapped fields which is not analyzed
				if ( $this->sort_field( $field ) ) {
					$field = "$field.sort";
				}

				$field = "$pid.$field";
			}

			if ( !isset( $sort[$field] ) ) {
				$sort[$field] = [ 'order' => $order ];
			}

			$chain = true;
		}
	}

	private function sort_field( $field ) {
		return strpos( $field, 'txt' ) !== false || strpos( $field, 'wpgField' ) !== false || strpos( $field, 'uriField' ) !== false;
	}

}