Generate 'signs style' query from the context
'+term1 term2 -term3 +(<subquery1>) ...'

@return Zend_Search_Lucene_Search_Query
548698
public function _signStyleExpressionQuery()
    {
        include_once 'Zend/Search/Lucene/Search/Query/Boolean.php';
        $query = new Zend_Search_Lucene_Search_Query_Boolean();

        include_once 'Zend/Search/Lucene/Search/QueryParser.php';
        if (Zend_Search_Lucene_Search_QueryParser::getDefaultOperator() == Zend_Search_Lucene_Search_QueryParser::B_AND) {
            $defaultSign = true; // required
        } else {
            // Zend_Search_Lucene_Search_QueryParser::B_OR
            $defaultSign = null; // optional
        }

        foreach ($this->_entries as $entryId => $entry) {
            $sign = ($this->_signs[$entryId] !== null) ?  $this->_signs[$entryId] : $defaultSign;
            $query->addSubquery($entry->getQuery($this->_encoding), $sign);
        }

        return $query;
    }
677123
public function getSearchResultByMySQL()
    {
        $queryParts = $this->getQueryParts();

        // build query
        $queryBuilder = self::getQueryBuilder('tx_kesearch_index');
        $queryBuilder->getRestrictions()->removeAll();
        $resultQuery = $queryBuilder
            ->add('select', $queryParts['SELECT'])
            ->from($queryParts['FROM'])
            ->add('where', $queryParts['WHERE']);
        if (!empty($queryParts['GROUPBY'])) {
            $resultQuery->add('groupBy', $queryParts['GROUPBY']);
        }
        if (!empty($queryParts['ORDERBY'])) {
            $resultQuery->add('orderBy', $queryParts['ORDERBY']);
        }

        $limit = $this->getLimit();
        if (is_array($limit)) {
            $resultQuery->setMaxResults(10);
            $resultQuery->setFirstResult($limit[0]);
        }

        // execute query
        $this->searchResults = $resultQuery->execute()->fetchAll();

        // log query
        if ($this->conf['logQuery']) {
            // @TODO use logging api https://docs.typo3.org/typo3cms/CoreApiReference/ApiOverview/Logging/Writers/Index.html
            GeneralUtility::devLog(
                'Search result query',
                $this->pObj->extKey,
                0,
                array($resultQuery->getSQL())
            );
        }

        $queryBuilder = self::getQueryBuilder('tx_kesearch_index');
        $queryBuilder->getRestrictions()->removeAll();
        $numRows = $queryBuilder
            ->add('select', 'FOUND_ROWS()')
            ->execute()
            ->fetchColumn(0);

        $this->numberOfResults = $numRows;

    }
510778
public function rewrite(Zend_Search_Lucene_Interface $index)
    {
        $this->_matches = array();

        if ($this->_pattern->field === null) {
            // Search through all fields
            $fields = $index->getFieldNames(true /* indexed fields list */);
        } else {
            $fields = array($this->_pattern->field);
        }

        $prefix          = self::_getPrefix($this->_pattern->text);
        $prefixLength    = strlen($prefix);
        $matchExpression = '/^' . str_replace(array('\\?', '\\*'), array('.', '.*'), preg_quote($this->_pattern->text, '/')) . '$/';

        if ($prefixLength < self::$_minPrefixLength) {
            include_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('At least ' . self::$_minPrefixLength . ' non-wildcard characters are required at the beginning of pattern.');
        }

        /**
 * @todo check for PCRE unicode support may be performed through Zend_Environment in some future 
*/
        if (@preg_match('/\pL/u', 'a') == 1) {
            // PCRE unicode support is turned on
            // add Unicode modifier to the match expression
            $matchExpression .= 'u';
        }

        $maxTerms = Zend_Search_Lucene::getTermsPerQueryLimit();
        foreach ($fields as $field) {
            $index->resetTermsStream();

            include_once 'Zend/Search/Lucene/Index/Term.php';
            if ($prefix != '') {
                $index->skipTo(new Zend_Search_Lucene_Index_Term($prefix, $field));

                while ($index->currentTerm() !== null          &&
                       $index->currentTerm()->field == $field  &&
                       substr($index->currentTerm()->text, 0, $prefixLength) == $prefix) {
                    if (preg_match($matchExpression, $index->currentTerm()->text) === 1) {
                        $this->_matches[] = $index->currentTerm();

                        if ($maxTerms != 0  &&  count($this->_matches) > $maxTerms) {
                            include_once 'Zend/Search/Lucene/Exception.php';
                            throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.');
                        }
                    }

                    $index->nextTerm();
                }
            } else {
                $index->skipTo(new Zend_Search_Lucene_Index_Term('', $field));

                while ($index->currentTerm() !== null  &&  $index->currentTerm()->field == $field) {
                    if (preg_match($matchExpression, $index->currentTerm()->text) === 1) {
                        $this->_matches[] = $index->currentTerm();

                        if ($maxTerms != 0  &&  count($this->_matches) > $maxTerms) {
                            include_once 'Zend/Search/Lucene/Exception.php';
                            throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.');
                        }
                    }

                    $index->nextTerm();
                }
            }

            $index->closeTermsStream();
        }

        if (count($this->_matches) == 0) {
            include_once 'Zend/Search/Lucene/Search/Query/Empty.php';
            return new Zend_Search_Lucene_Search_Query_Empty();
        } else if (count($this->_matches) == 1) {
            include_once 'Zend/Search/Lucene/Search/Query/Term.php';
            return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches));
        } else {
            include_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php';
            $rewrittenQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();

            foreach ($this->_matches as $matchedTerm) {
                $rewrittenQuery->addTerm($matchedTerm);
            }

            return $rewrittenQuery;
        }
    }
154699
public function buildQuery()
    {
        $this->setSelectFrom();
        $this->setLeftJoins($this->qb);
        $this->setWhere($this->qb);
        $this->setWhereResultCallback($this->qb);
        $this->setWhereAllCallback($this->qb);
        $this->setOrderBy();
        $this->setLimit();

        return $this;
    }
127045
public function getSearchResultBySphinx()
    {
        /** @var KeSearchPremium keSearchPremium */
        $this->keSearchPremium = GeneralUtility::makeInstance(KeSearchPremium::class);

        // set ordering
        $this->keSearchPremium->setSorting($this->getOrdering());

        // set limit
        $limit = $this->getLimit();
        $this->keSearchPremium->setLimit($limit[0], $limit[1], intval($this->pObj->extConfPremium['sphinxLimit']));

        // generate query
        $queryForSphinx = '';
        if ($this->pObj->wordsAgainst) {
            $queryForSphinx .= ' @(title,content) ' . $this->escapeString($this->pObj->wordsAgainst);
        }
        if (count($this->pObj->tagsAgainst)) {
            foreach ($this->pObj->tagsAgainst as $value) {
                // in normal case only checkbox mode has spaces
                $queryForSphinx .= ' @tags ' . str_replace('" "', '" | "', trim($value));
            }
        }

        // add language
        $queryForSphinx .= ' @language _language_-1 | _language_' . $GLOBALS['TSFE']->sys_language_uid;

        // add fe_groups to query
        $queryForSphinx .= ' @fe_group _group_NULL | _group_0';

        $context = GeneralUtility::makeInstance(Context::class);
        $feGroups = $context->getPropertyFromAspect('frontend.user', 'groupIds');
        if (count($feGroups)) {
            foreach ($feGroups as $key => $group) {
                $intval_positive_group = MathUtility::convertToPositiveInteger($group);
                if ($intval_positive_group) {
                    $feGroups[$key] = '_group_' . $group;
                } else {
                    unset($feGroups[$key]);
                }
            }
            if (is_array($feGroups) && count($feGroups)) {
                $queryForSphinx .= ' | ' . implode(' | ', $feGroups);
            }
        }

        // restrict to storage page (in MySQL: $where .= ' AND pid in (' .  . ') ';)
        $startingPoints = GeneralUtility::trimExplode(',', $this->pObj->startingPoints);
        $queryForSphinx .= ' @pid ';
        $first = true;
        foreach ($startingPoints as $startingPoint) {
            if (!$first) {
                $queryForSphinx .= ' | ';
            } else {
                $first = false;
            }

            $queryForSphinx .= ' _pid_' . $startingPoint;
        }

        // hook for appending additional where clause to sphinx query
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['ke_search']['appendWhereToSphinx'])) {
            foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['ke_search']['appendWhereToSphinx'] as $_classRef) {
                $_procObj = &GeneralUtility::makeInstance($_classRef);
                $queryForSphinx = $_procObj->appendWhereToSphinx($queryForSphinx, $this->keSearchPremium, $this);
            }
        }
        $rows = $this->keSearchPremium->getSearchResults($queryForSphinx);

        // get number of records
        $this->numberOfResults = $this->keSearchPremium->getTotalFound();
        return $rows;
    }
1241325
public function actionIndex()
    {
        $searchModel = new TermTypeSearch();
        $dataProvider = $searchModel->search(request()->queryParams);

        return $this->render('index', [
            'searchModel'  => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
97659
public function merge()
    {
        if ($this->_mergeDone) {
            include_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('Merge is already done.');
        }

        if (count($this->_segmentInfos) < 1) {
            include_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception(
                'Wrong number of segments to be merged ('
                                                 . count($this->_segmentInfos)
                . ').'
            );
        }

        $this->_mergeFields();
        $this->_mergeNorms();
        $this->_mergeStoredFields();
        $this->_mergeTerms();

        $this->_mergeDone = true;

        return $this->_writer->close();
    }
1194873
public static function getResultSetLimit()
    {
        if (count($this->_indices) == 0) {
            include_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('Indices list is empty');
        }

        $defaultResultSetLimit = reset($this->_indices)->getResultSetLimit();

        foreach ($this->_indices as $index) {
            if ($index->getResultSetLimit() !== $defaultResultSetLimit) {
                include_once 'Zend/Search/Lucene/Exception.php';
                throw new Zend_Search_Lucene_Exception('Indices have different default search field.');
            }
        }

        return $defaultResultSetLimit;
    }
158839
public function openedRQLastTerm()
    {
        $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_rqFirstTerm, $this->_encoding);
        if (count($tokens) > 1) {
            include_once 'Zend/Search/Lucene/Search/QueryParserException.php';
            throw new Zend_Search_Lucene_Search_QueryParserException('Range query boundary terms must be non-multiple word terms');
        } else if (count($tokens) == 1) {
            include_once 'Zend/Search/Lucene/Index/Term.php';
            $from = new Zend_Search_Lucene_Index_Term(reset($tokens)->getTermText(), $this->_context->getField());
        } else {
            $from = null;
        }

        $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_currentToken->text, $this->_encoding);
        if (count($tokens) > 1) {
            include_once 'Zend/Search/Lucene/Search/QueryParserException.php';
            throw new Zend_Search_Lucene_Search_QueryParserException('Range query boundary terms must be non-multiple word terms');
        } else if (count($tokens) == 1) {
            include_once 'Zend/Search/Lucene/Index/Term.php';
            $to = new Zend_Search_Lucene_Index_Term(reset($tokens)->getTermText(), $this->_context->getField());
        } else {
            $to = null;
        }

        if ($from === null  &&  $to === null) {
            include_once 'Zend/Search/Lucene/Search/QueryParserException.php';
            throw new Zend_Search_Lucene_Search_QueryParserException('At least one range query boundary term must be non-empty term');
        }

        include_once 'Zend/Search/Lucene/Search/Query/Range.php';
        $rangeQuery = new Zend_Search_Lucene_Search_Query_Range($from, $to, false);
        include_once 'Zend/Search/Lucene/Search/QueryEntry/Subquery.php';
        $entry      = new Zend_Search_Lucene_Search_QueryEntry_Subquery($rangeQuery);
        $this->_context->addEntry($entry);
    }
305419
protected function scanEOS()
    {
        if (!$this->length()) {

            if (count($this->indentStack)) {
                array_shift($this->indentStack);

                return $this->token('outdent');
            }

            return $this->token('eos');
        }
    }
766805
protected function getSearchFields()
    {
        if (null == $this->searchFields) {
            $field = $this->getEntityDescriptor()->getDisplayFiled();
            $this->searchFields = [
                $this->getEntityDescriptor()
                    ->getTableName().'.'.$field->getField()
            ];
        }
        return $this->searchFields;
    }
1321618
public function columnSearch()
    {
        $columns = $this->request->get('columns', []);

        foreach ($columns as $index => $column) {

            if (!$this->request->isColumnSearchable($index)) {
                continue;
            }

            $column = $this->getColumnName($index);

            if (isset($this->columnDef['filter'][$column])) {
                $columnDef = $this->columnDef['filter'][$column];
                // get a raw keyword (without wildcards)
                $keyword   = $this->getSearchKeyword($index, true);
                $builder   = $this->getQueryBuilder();

                if ($columnDef['method'] instanceof Closure) {
                    $whereQuery = $builder->newQuery();
                    call_user_func_array($columnDef['method'], [$whereQuery, $keyword]);
                    $builder->addNestedWhereQuery($whereQuery);
                } else {
                    $this->compileColumnQuery(
                            $builder, $columnDef['method'], $columnDef['parameters'], $column, $keyword
                    );
                }
            } else {
                if (count(explode('.', $column)) > 1) {
                    $eagerLoads     = $this->getEagerLoads();
                    $parts          = explode('.', $column);
                    $relationColumn = array_pop($parts);
                    $relation       = implode('.', $parts);
                    if (in_array($relation, $eagerLoads)) {
                        $column = $this->joinEagerLoadedColumn($relation, $relationColumn);
                    }
                }

                $column          = $this->castColumn($column);
                $keyword         = $this->getSearchKeyword($index);
                $caseInsensitive = $this->isCaseInsensitive();

                if (!$caseInsensitive) {
                    $column = strstr($column, '(') ? $this->connection->raw($column) : $column;
                }

                $this->compileColumnSearch($index, $column, $keyword, $caseInsensitive);
            }

            $this->isFilterApplied = true;
        }
    }
347253
public function getQueryTerms()
    {
        if ($this->_signs === null) {
            return $this->_terms;
        }

        $terms = array();

        foreach ($this->_signs as $id => $sign) {
            if ($sign !== false) {
                $terms[] = $this->_terms[$id];
            }
        }

        return $terms;
    }
1254340
public function optimize(Zend_Search_Lucene_Interface $index)
    {
        // Check, that index contains all phrase terms
        foreach ($this->_terms as $term) {
            if (!$index->hasTerm($term)) {
                include_once 'Zend/Search/Lucene/Search/Query/Empty.php';
                return new Zend_Search_Lucene_Search_Query_Empty();
            }
        }

        if (count($this->_terms) == 1) {
            // It's one term query
            include_once 'Zend/Search/Lucene/Search/Query/Term.php';
            $optimizedQuery = new Zend_Search_Lucene_Search_Query_Term(reset($this->_terms));
            $optimizedQuery->setBoost($this->getBoost());

            return $optimizedQuery;
        }

        if (count($this->_terms) == 0) {
            include_once 'Zend/Search/Lucene/Search/Query/Empty.php';
            return new Zend_Search_Lucene_Search_Query_Empty();
        }


        return $this;
    }
818684
private function getSearchSuggestions()
    {
        $tokens = $this->getTokens();
        $allResults = array();
        foreach ($tokens as $token) {
            $allResults = $this->getSearchSuggestion($token, $allResults);
        }
        return $allResults;
    }
44043
public function getSPARQL() {
		// add subqueries to the beginning because they are logically evaluated first
		$sparql = $this->formatSubqueries();

		foreach ( $this->conditions as $subject => $predicates ) {
			$sparql .= ' ' . $subject;
			$sparql .= $this->formatPredicates( $predicates ) . ' .';
		}

		$sparql .= $this->formatOptionals();
		$sparql .= $this->formatFilters();
		$sparql .= $this->formatUnions();

		return $sparql;
	}
300903
private function _getIndexWriter()
    {
        if ($this->_writer === null) {
            include_once 'Zend/Search/Lucene/Index/Writer.php';
            $this->_writer = new Zend_Search_Lucene_Index_Writer(
                $this->_directory,
                $this->_segmentInfos,
                $this->_formatVersion
            );
        }

        return $this->_writer;
    }