common terms query.

@see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-common-terms-query.html

@param string $field
@param string $query
@param float  $cutoffFrequency percentage in decimal form (.001 == 0.1%)

@return Common
426950
public function common_terms(string $field, string $query, float $cutoffFrequency): Common
    {
        return new Common($field, $query, $cutoffFrequency);
    }
582620
public function whereTerms(string $field, array $query)
    {
        $param = [
            "terms" => [
                $field => $query
            ]
        ];

        $this->elasticQuery[] = $param;
        return $this;
    }
972937
protected function getFieldQuery ($field, $searchOper, $term, QueryBuilder $qb)
    {
        if(is_array($this->searchableProperties) && !in_array($field, $this->searchableProperties)){
            throw new \Exception(sprintf('Field %s is not searchable', $field));
        }

        switch ($searchOper) {
            case 'eq':
                return $qb->expr()->eq($field, $qb->expr()->literal($term));
                 
            case 'ne':
                return $qb->expr()->neq($field, $qb->expr()->literal($term));
                 
            case 'lt':
                return $qb->expr()->lt($field, $qb->expr()->literal($term));
                 
            case 'le':
                return $qb->expr()->lte($field, $qb->expr()->literal($term));
                 
            case 'gt':
                return $qb->expr()->gt($field, $qb->expr()->literal($term));
                 
            case 'ge':
                return $qb->expr()->gte($field, $qb->expr()->literal($term));
                 
            case 'bw':
                return $qb->expr()->like($field, $qb->expr()->literal($term . '%'));
    
            case 'bn':
                return $qb->expr()->not($qb->expr()->like($field, $qb->expr()->literal($term . '%')));
                 
            case 'ew':
                return $qb->expr()->like($field, $qb->expr()->literal('%' . $term));
    
            case 'en':
                return $qb->expr()->not($qb->expr()->like($field, $qb->expr()->literal('%' . $term)));
    
            case 'cn':
                return $qb->expr()->like($field, $qb->expr()->literal('%' . $term . '%'));
    
            case 'nc':
                return $qb->expr()->not($qb->expr()->like($field, $qb->expr()->literal('%' . $term . '%')));
    
            default:
                throw new \InvalidArgumentException(sprintf('Search operator %s is not valid', $searchOper));
        }
    }
500937
public function scopeOfField ($query, $fieldName)
  {
    $fieldName = str_segmentsLast ($fieldName, '.');
    return exists ($fieldName) ? $query->where ('group', $fieldName) : $query;
  }
1143868
protected function dsn_select($query)
    {
        // no replication
        if ($this->db_dsnw == $this->db_dsnr) {
            return 'w';
        }

        // Read or write ?
        $mode = preg_match('/^(select|show|set)/i', $query) ? 'r' : 'w';

        $start = '[' . $this->options['identifier_start'] . self::DEFAULT_QUOTE . ']';
        $end   = '[' . $this->options['identifier_end']   . self::DEFAULT_QUOTE . ']';
        $regex = '/(?:^|\s)(from|update|into|join)\s+'.$start.'?([a-z0-9._]+)'.$end.'?\s+/i';

        // find tables involved in this query
        if (preg_match_all($regex, $query, $matches, PREG_SET_ORDER)) {
            foreach ($matches as $m) {
                $table = $m[2];

                // always use direct mapping
                if ($this->options['table_dsn_map'][$table]) {
                    $mode = $this->options['table_dsn_map'][$table];
                    break;  // primary table rules
                }
                else if ($mode == 'r') {
                    // connected to db with the same or "higher" mode for this table
                    $db_mode = $this->table_connections[$table];
                    if ($db_mode == 'w' && !$this->options['dsnw_noread']) {
                        $mode = $db_mode;
                    }
                }
            }

            // remember mode chosen (for primary table)
            $table = $matches[0][2];
            $this->table_connections[$table] = $mode;
        }

        return $mode;
    }
938613
public static function filterRangeDate(
        QueryBuilder $queryBuilder,
        &$criteria,
        $field,
        $fieldFrom,
        $fieldTo,
        $alias = 'o'
    ) {
        if (isset($criteria[$fieldFrom]) || isset($criteria[$fieldTo]) && $criteria[$fieldTo] != '') {
            if (!empty($criteria[$fieldFrom])) {
                $from = $criteria[$fieldFrom].' 00:00:00';
                $queryBuilder
                    ->andWhere($queryBuilder->expr()->gte(sprintf('%s.%s', $alias, $field), sprintf(':%s', $fieldFrom)))
                    ->setParameter($fieldFrom, \DateTime::createFromFormat('d/m/Y H:i:s', $from));
            }
            unset($criteria[$fieldFrom]);
            if (!empty($criteria[$fieldTo])) {
                $to = $criteria[$fieldTo].' 23:59:59';
                $queryBuilder
                    ->andWhere($queryBuilder->expr()->lte(sprintf('%s.%s', $alias, $field), sprintf(':%s', $fieldTo)))
                    ->setParameter($fieldTo, \DateTime::createFromFormat('d/m/Y H:i:s', $to));
            }
            unset($criteria[$fieldTo]);
        }

        return $criteria;
    }
46970
public function getRelationCountQueryForSelfRelation(Builder $query, Builder $parent)
	{
		$query->select(new Expression('count(*)'));

		$query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());

		$key = $this->wrap($this->getQualifiedForeignKey());

		return $query->where($hash.'.'.$query->getModel()->getKeyName(), '=', new Expression($key));
	}
1306863
protected function rawQuery($query)
	{
		$start = microtime(TRUE);
		$res   = mysqli_query($this->conn, $query);
		$timer = microtime(TRUE) - $start;

		$this->stats[] = array(
			'query' => $query,
			'start' => $start,
			'timer' => $timer,
		);
		if (!$res)
		{
			$error = mysqli_error($this->conn);
			
			end($this->stats);
			$key = key($this->stats);
			$this->stats[$key]['error'] = $error;
			$this->cutStats();
			
			$this->error("$error. Full query: [$query]");
		}
		$this->cutStats();
		return $res;
	}
1202878
public function distinct(Query $query, $field)
    {
        $options = $query->getOptions();

        $cmd = [
            'distinct' => $options['table'],
            'key'      => $field,
        ];

        if (!empty($options['where'])) {
            $cmd['query'] = $this->parseWhere($query, $options['where']);
        }

        if (isset($options['maxTimeMS'])) {
            $cmd['maxTimeMS'] = $options['maxTimeMS'];
        }

        $command = new Command($cmd);

        $this->log('cmd', 'distinct', $cmd);

        return $command;
    }
323240
protected long cutOffToFrequency(long cutOff, int flt_modifier, boolean isExFilterRange)
	{
		double fac = (isExFilterRange)?(20.0d*512.0d):(24.0d*512.0d);
		double fc = 110.0d * Math.pow(2.0d, 0.25d + ((double)(cutOff*(flt_modifier+256))) / fac);
		long freq = (long)fc;
		if (freq<120) return 120;
		if (freq>20000) return 20000;
		if ((freq<<1) > sampleRate) return ((long)sampleRate)>>1;
		return freq;
	}
31204
public function scopeWithTranslation(Builder $query)
    {
        $query->with([
            'translations' => function (Relation $query) {
                if ($this->useFallback()) {
                    $locale = $this->locale();
                    $countryFallbackLocale = $this->getFallbackLocale($locale); // e.g. de-DE => de
                    $locales = array_unique([$locale, $countryFallbackLocale, $this->getFallbackLocale()]);

                    return $query->whereIn($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locales);
                }

                return $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
            },
        ]);
    }
1227325
public static function moreLikeThis(Array $fields, Array $ids, $minTermFreq = 1, $percentTermsToMatch = 0.5, $minWordLength = 3)
    {
        $body = array(
            'query' => array(
                'more_like_this' => array(
                    'fields' => $fields,
                    'ids' => $ids,
                    'min_term_freq' => $minTermFreq,
                    'percent_terms_to_match' => $percentTermsToMatch,
                    'min_word_length' => $minWordLength,
                )
            ),
            'size' => 1000
        );

        return static::search($body);
    }
573328
public function scopeWithTerms($query, $terms, $taxonomy)
    {
        $terms = TaxableUtils::makeTermsArray($terms);

        foreach ($terms as $term)
            $this->scopeWithTerm($query, $term, $taxonomy);

        return $query;
    }
161778
private function applyFieldFilter(Builder $query, $field, $value)
    {
        $query = $this->resolveOrLinks($query, $field, $value);

        return $query;
    }
104873
private function applyFilters(AbstractQueryBuilder $query)
    {
        //GroupBy is only applicable to Select
        if ($query instanceof Select) {
            if (isset($this->groupByFields)) {
                $query->groupBy($this->groupByFields);
            }
            $this->joinRelationsToQuery($this->entity, $query, $this->with);
        }
        if (isset($this->where)) {
            $query->where($this->where);
        }
        foreach ($this->orderByFields as $field) {
            list($fieldName, $order) = $field;
            $query->orderBy($fieldName, $order);
        }
        if (empty($this->with)) {
            //Limits for joined queries are handled in a different way
            if (isset($this->limit)) {
                $query->setMaxResults($this->limit);
            }
            if (isset($this->offset)) {
                $query->setFirstResult($this->offset);
            }
        }

        return $query;
    }
379862
public function defineSearch($query, $type)
    {
        $query = Util::escapeTerm($query);

        $elasticaQueryString = new Match();
        $elasticaQueryString
            ->setFieldMinimumShouldMatch('content', '80%')
            ->setFieldQuery('content', $query);

        if ($this->useMatchQueryForTitle) {
            $elasticaQueryTitle = new Match();
            $elasticaQueryTitle
              ->setFieldQuery('title', $query)
              ->setFieldMinimumShouldMatch('title', '80%')
              ->setFieldBoost(2);
        } else {
            $elasticaQueryTitle = new QueryString();
            $elasticaQueryTitle
              ->setDefaultField('title')
              ->setQuery($query);
        }

        $elasticaQueryBool = new BoolQuery();
        $elasticaQueryBool
            ->addShould($elasticaQueryTitle)
            ->addShould($elasticaQueryString)
            ->setMinimumShouldMatch(1);

        $this->applySecurityFilter($elasticaQueryBool);

        if (!is_null($type)) {
            $elasticaQueryType = new Term();
            $elasticaQueryType->setTerm('type', $type);
            $elasticaQueryBool->addMust($elasticaQueryType);
        }

        $rootNode = $this->domainConfiguration->getRootNode();
        if (!is_null($rootNode)) {
            $elasticaQueryRoot = new Term();
            $elasticaQueryRoot->setTerm('root_id', $rootNode->getId());
            $elasticaQueryBool->addMust($elasticaQueryRoot);
        }

        $rescore = new \Elastica\Rescore\Query();
        $rescore->setRescoreQuery($this->getPageBoosts());

        $this->query->setQuery($elasticaQueryBool);
        $this->query->setRescore($rescore);
        $this->query->setHighlight(
            array(
                'pre_tags' => array('<strong>'),
                'post_tags' => array('</strong>'),
                'fields' => array(
                    'content' => array(
                        'fragment_size' => 150,
                        'number_of_fragments' => 3,
                    ),
                ),
            )
        );
    }
623479
public function scopeTerm($query, $term, $taxonomy = 'major')
    {
        return $query->whereHas('term', function($q) use($term, $taxonomy) {
            $q->where('name', $term);
        });
    }