// search performs the actual search on each conversation after it completes
// preSearch via `preSearchCh`
16192
func (s *searchSession) search(ctx context.Context) (err error) {
	defer s.indexer.Trace(ctx, func() error { return err }, "searchSession.search")()
	for _, conv := range s.convList {
		select {
		case <-ctx.Done():
			return ctx.Err()
		default:
		}
		if err := s.searchConvWithUIUpdate(ctx, conv.GetConvID()); err != nil {
			return err
		}
		if s.searchDone(ctx, "search") {
			return nil
		}
	}
	return nil
}
190612
func (i *ComponentInput) Search() error {
	if i.Searcher == nil {
		return ErrNoMatch{Value: i.Value, Qualifier: "no searcher defined"}
	}
	matches, err := i.Searcher.Search(false, i.Value)
	if matches != nil {
		i.SearchMatches = matches
	}
	return errors.NewAggregate(err)
}
870147
func NewSearch(c *Connection, q *Query) *Search {
	s := new(Search)
	if q != nil {
		s.SetQuery(q)
	}

	if c != nil {
		s.conn = c
	}
	return s
}
550785
func (c *Cursor) search(key []byte, pgid pgid) {
	p, n := c.bucket.pageNode(pgid)
	if p != nil && (p.flags&(branchPageFlag|leafPageFlag)) == 0 {
		panic(fmt.Sprintf("invalid page type: %d: %x", p.id, p.flags))
	}
	e := elemRef{page: p, node: n}
	c.stack = append(c.stack, e)

	// If we're on a leaf page/node then find the specific node.
	if e.isLeaf() {
		c.nsearch(key)
		return
	}

	if n != nil {
		c.searchNode(key, n)
		return
	}
	c.searchPage(key, p)
}
266325
func (c *CredentialGraphClient) Search(ctx context.Context, pathExp string,
	ownerID *identity.ID, teamIDs []identity.ID) ([]CredentialGraph, error) {

	query := url.Values{}

	query.Set("pathexp", pathExp)
	query.Set("owner_id", ownerID.String())
	query.Set("mode", "contains")

	for _, id := range teamIDs {
		query.Add("team_id", id.String())
	}

	return c.getGraph(ctx, query)
}
438836
func (s *searchSession) searchConv(ctx context.Context, convID chat1.ConversationID) (msgIDs []chat1.MessageID, err error) {
	defer s.indexer.Trace(ctx, func() error { return err }, fmt.Sprintf("searchConv convID: %s", convID))()
	var allMsgIDs mapset.Set
	for token := range s.tokens {
		matchedIDs := mapset.NewThreadUnsafeSet()
		idMap, err := s.indexer.store.GetHits(ctx, s.uid, convID, token)
		if err != nil {
			return nil, err
		}
		for msgID := range idMap {
			matchedIDs.Add(msgID)
		}
		if allMsgIDs == nil {
			allMsgIDs = matchedIDs
		} else {
			allMsgIDs = allMsgIDs.Intersect(matchedIDs)
			if allMsgIDs.Cardinality() == 0 {
				// no matches in this conversation..
				return nil, nil
			}
		}
	}
	msgIDSlice := msgIDsFromSet(allMsgIDs)

	// Sort so we can truncate if necessary, returning the newest results first.
	sort.Sort(utils.ByMsgID(msgIDSlice))
	return msgIDSlice, nil
}
1109002
func NewSearchRequest(
	BaseDN string,
	Scope, DerefAliases, SizeLimit, TimeLimit int,
	TypesOnly bool,
	Filter string,
	Attributes []string,
	Controls []Control,
) *SearchRequest {
	return &SearchRequest{
		BaseDN:       BaseDN,
		Scope:        Scope,
		DerefAliases: DerefAliases,
		SizeLimit:    SizeLimit,
		TimeLimit:    TimeLimit,
		TypesOnly:    TypesOnly,
		Filter:       Filter,
		Attributes:   Attributes,
		Controls:     Controls,
	}
}
1038092
func (r *GormSearchRepository) search(ctx context.Context, sqlSearchQueryParameter string, workItemTypes []uuid.UUID, start *int, limit *int, spaceID *string) ([]workitem.WorkItemStorage, int, error) {
	db := r.db.Model(workitem.WorkItemStorage{}).Where("tsv @@ query")
	if start != nil {
		if *start < 0 {
			return nil, 0, errors.NewBadParameterError("start", *start)
		}
		db = db.Offset(*start)
	}
	if limit != nil {
		if *limit <= 0 {
			return nil, 0, errors.NewBadParameterError("limit", *limit)
		}
		db = db.Limit(*limit)
	}
	if len(workItemTypes) > 0 {
		// restrict to all given types and their subtypes
		query := fmt.Sprintf("%[1]s.type in ("+
			"select distinct subtype.id from %[2]s subtype "+
			"join %[2]s supertype on subtype.path <@ supertype.path "+
			"where supertype.id in (?))", workitem.WorkItemStorage{}.TableName(), workitem.WorkItemType{}.TableName())
		db = db.Where(query, workItemTypes)
	}

	db = db.Select("count(*) over () as cnt2 , *").Order(workitem.Column(workitem.WorkItemStorage{}.TableName(), "execution_order") + " desc")
	db = db.Joins(", to_tsquery('english', ?) as query, ts_rank(tsv, query) as rank", sqlSearchQueryParameter)
	if spaceID != nil {
		db = db.Where("space_id=?", *spaceID)
	}
	db = db.Order(fmt.Sprintf("rank desc,%s.updated_at desc", workitem.WorkItemStorage{}.TableName()))

	rows, err := db.Rows()
	defer closeable.Close(ctx, rows)
	if err != nil {
		return nil, 0, errs.Wrapf(err, "failed to execute search query")
	}

	result := []workitem.WorkItemStorage{}
	value := workitem.WorkItemStorage{}
	columns, err := rows.Columns()
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"err": err,
		}, "failed to get column names")
		return nil, 0, errors.NewInternalError(ctx, errs.Wrap(err, "failed to get column names"))
	}

	// need to set up a result for Scan() in order to extract total count.
	var count int
	var ignore interface{}
	columnValues := make([]interface{}, len(columns))

	for index := range columnValues {
		columnValues[index] = &ignore
	}
	columnValues[0] = &count
	first := true

	for rows.Next() {
		db.ScanRows(rows, &value)
		if first {
			first = false
			if err = rows.Scan(columnValues...); err != nil {
				log.Error(ctx, map[string]interface{}{
					"err": err,
				}, "failed to scan rows")
				return nil, 0, errors.NewInternalError(ctx, errs.Wrap(err, "failed to scan rows"))
			}
		}
		result = append(result, value)

	}
	if first {
		// means 0 rows were returned from the first query,
		count = 0
	}
	log.Info(ctx, nil, "Search results: %d matches", count)
	return result, count, nil
	//*/
}
924054
func (exp *explorerUI) Search(w http.ResponseWriter, r *http.Request) {
	// The ?search= query.
	searchStr := r.URL.Query().Get("search")

	// Strip leading and tailing whitespace.
	searchStr = strings.TrimSpace(searchStr)

	if searchStr == "" {
		exp.StatusPage(w, "search failed", "The search term was empty.",
			searchStr, ExpStatusBadRequest)
		return
	}

	// Attempt to get a block hash by calling GetBlockHash of WiredDB or
	// BlockHash of ChainDB to see if the URL query value is a block index. Then
	// redirect to the block page if it is.
	idx, err := strconv.ParseInt(searchStr, 10, 0)
	if err == nil {
		_, err = exp.blockData.GetBlockHash(idx)
		if err == nil {
			http.Redirect(w, r, "/block/"+searchStr, http.StatusPermanentRedirect)
			return
		}
		_, err = exp.explorerSource.BlockHash(idx)
		if err == nil {
			http.Redirect(w, r, "/block/"+searchStr, http.StatusPermanentRedirect)
			return
		}
		exp.StatusPage(w, "search failed", "Block "+searchStr+
			" has not yet been mined", searchStr, ExpStatusNotFound)
		return
	}

	// Call GetExplorerAddress to see if the value is an address hash and
	// then redirect to the address page if it is.
	address, _, addrErr := exp.blockData.GetExplorerAddress(searchStr, 1, 0)
	switch addrErr {
	case txhelpers.AddressErrorNoError, txhelpers.AddressErrorZeroAddress:
		http.Redirect(w, r, "/address/"+searchStr, http.StatusPermanentRedirect)
		return
	case txhelpers.AddressErrorWrongNet:
		// Status page will provide a link, but the address page can too.
		message := fmt.Sprintf("The address %v is valid on %s, not %s",
			searchStr, address.Net, exp.NetName)
		exp.StatusPage(w, wrongNetwork, message, searchStr, ExpStatusWrongNetwork)
		return
	}

	// This is be unnecessarily duplicative and possible very slow for a very
	// active addresss.
	addrHist, _, _ := exp.explorerSource.AddressHistory(searchStr,
		1, 0, dbtypes.AddrTxnAll)
	if len(addrHist) > 0 {
		http.Redirect(w, r, "/address/"+searchStr, http.StatusPermanentRedirect)
		return
	}

	// Remaining possibilities are hashes, so verify the string is a hash.
	if _, err = chainhash.NewHashFromStr(searchStr); err != nil {
		exp.StatusPage(w, "search failed",
			"Search string is not a valid hash or address: "+searchStr,
			"", ExpStatusNotFound)
		return
	}

	// Attempt to get a block index by calling GetBlockHeight to see if the
	// value is a block hash and then redirect to the block page if it is.
	_, err = exp.blockData.GetBlockHeight(searchStr)
	// If block search failed, check the aux DB, which has data for side chain
	// and orphaned blocks.
	if err != nil {
		_, err = exp.explorerSource.BlockHeight(searchStr)
	}
	if err == nil {
		http.Redirect(w, r, "/block/"+searchStr, http.StatusPermanentRedirect)
		return
	}

	// Call GetExplorerTx to see if the value is a transaction hash and then
	// redirect to the tx page if it is.
	tx := exp.blockData.GetExplorerTx(searchStr)
	if tx != nil {
		http.Redirect(w, r, "/tx/"+searchStr, http.StatusPermanentRedirect)
		return
	}

	// Also check the aux DB as it may have transactions from orphaned blocks.
	dbTxs, err := exp.explorerSource.Transaction(searchStr)
	if err != nil && err != sql.ErrNoRows {
		log.Errorf("Searching for transaction failed: %v", err)
	}
	if dbTxs != nil {
		http.Redirect(w, r, "/tx/"+searchStr, http.StatusPermanentRedirect)
		return
	}

	// Check if the search term references a proposal token.
	proposalInfo, err := exp.proposalsSource.ProposalByToken(searchStr)
	if err == nil && proposalInfo.RefID != "" {
		http.Redirect(w, r, "/proposal/"+proposalInfo.RefID, http.StatusPermanentRedirect)
		return
	}

	message := "The search did not find any matching address, block, transaction or proposal token: " + searchStr
	exp.StatusPage(w, "search failed", message, "", ExpStatusNotFound)
}
908185
func (this *Client) Search(args SearchArgs, resp interface{}) error {
	return this.InvokeByAnyMethod(http.MethodGet, "", "/search", args, resp)
}
1089331
func (s *Store) Search(ctx context.Context, key schema.AMKey, ttl, start, end uint32) ([]chunk.IterGen, error) {
	log.Debugf("btStore: fetching chunks for metric %s in range %d %d", key, start, end)
	_, span := tracing.NewSpan(ctx, s.tracer, "BigtableStore.Search")
	defer span.Finish()
	tags.SpanKindRPCClient.Set(span)
	tags.PeerService.Set(span, "bigtable")

	itgens := make([]chunk.IterGen, 0)
	if start > end {
		tracing.Failure(span)
		tracing.Error(span, errStartBeforeEnd)
		return itgens, errStartBeforeEnd
	}

	// limit number of inflight requests
	log.Debugf("btStore: waiting for Search slot. len=%d cap=%d", len(s.readLimiter), cap(s.readLimiter))
	pre := time.Now()
	if !s.readLimiter.Acquire(ctx) {
		return itgens, errCtxCanceled
	}
	log.Debug("btStore: acquired a Search slot")
	btblGetWaitDuration.Value(time.Since(pre))

	startMonth := start / Month_sec   // starting row has to be at, or before, requested start
	endMonth := (end - 1) / Month_sec // ending row has to include the last point we might need (end-1)

	// unfortunately in the database we only have the t0's of all chunks.
	// this means we can easily make sure to include the correct last chunk (just query for a t0 < end, the last chunk will contain the last needed data)
	// but it becomes hard to find which should be the first chunk to include. we can't just query for start <= t0 because then we will miss some data at
	// the beginning. We can't assume we know the chunkSpan so we can't just calculate the t0 >= (start - <some-predefined-number>) because ChunkSpans
	// may change over time.
	// We effectively need all chunks with a t0 > start, as well as the last chunk with a t0 <= start.
	// Bigtable doesn't allow us to fetch the most recent chunk older then start, so instead we just fetch from (start - maxChunkSpan) to enure we get the data. This
	// will usually result in more data being fetched then is needed, but that is an acceptable tradeoff.
	adjustedStart := start - uint32(s.cfg.MaxChunkSpan.Seconds())

	// chunkspans are aligned with Month_sec.  If start is > startMonth*Month_sec then the T0 of the chunk that start is in will also be >= startMonth*Month_sec.
	adjustedStart = util.Max(adjustedStart, startMonth*Month_sec)

	agg := "raw"
	var intervalHint uint32
	if key.Archive > 0 {
		agg = key.Archive.String()
		intervalHint = key.Archive.Span()
	}
	// filter the results to just the agg method (Eg raw, min_60, max_1800, etc..) and the timerange we want.
	// we fetch all columnFamilies (which are the different TTLs).  Typically there will be only one columnFamily
	// that has data, unless the TTL of the agg has changed.  In which case we want all columnFamilies anyway.
	filter := bigtable.ChainFilters(
		bigtable.ColumnFilter(agg),
		bigtable.TimestampRangeFilterMicros(bigtable.Timestamp(int64(adjustedStart)*1e6), bigtable.Timestamp(int64(end)*1e6)),
	)

	firstRow := formatRowKey(key, startMonth)
	lastRow := formatRowKey(key, endMonth+1) // bigtable.RowRange is start inclusive, end exclusive
	rr := bigtable.NewRange(firstRow, lastRow)
	var err error
	rowCount := 0
	pre = time.Now()
	queryCtx, cancel := context.WithTimeout(ctx, s.cfg.ReadTimeout)
	reqErr := s.tbl.ReadRows(queryCtx, rr, func(row bigtable.Row) bool {
		rowCount++
		chunks := 0
		var itgen chunk.IterGen
		for _, items := range row {
			for _, rItem := range items {
				chunkSizeAtLoad.Value(len(rItem.Value))
				if len(rItem.Value) < 2 {
					log.Errorf("btStore: bigtable readRows error. %s", err)
					err = errChunkTooSmall
					return false
				}
				itgen, err = chunk.NewIterGen(uint32(rItem.Timestamp/1e6), intervalHint, rItem.Value)
				if err != nil {
					log.Errorf("btStore: unable to create chunk from bytes. %s", err)
					return false
				}
				chunks++

				// This function is called serially so we don't need synchronization here
				itgens = append(itgens, itgen)
			}
		}
		btblChunksPerRow.Value(chunks)

		return true
	}, bigtable.RowFilter(filter))
	cancel()
	btblRowsPerResponse.Value(rowCount)
	btblGetExecDuration.Value(time.Since(pre))

	// free a slot in the readLimiter
	s.readLimiter.Release()

	if reqErr != nil {
		log.Errorf("btStore: bigtable readRows error. %s", reqErr)
		err = reqErr
	}
	if err != nil {
		tracing.Failure(span)
		tracing.Error(span, err)
		btblReadError.Inc()
	}
	// TODO: do we need to ensure that itgens is sorted by chunk T0?
	sort.Sort(chunk.IterGensAsc(itgens))
	return itgens, err
}
642096
func (s *SearchService) Do(ctx context.Context) (*SearchResult, error) {
	// Check pre-conditions
	if err := s.Validate(); err != nil {
		return nil, err
	}

	// Get URL for request
	path, params, err := s.buildURL()
	if err != nil {
		return nil, err
	}

	// Perform request
	var body interface{}
	if s.source != nil {
		body = s.source
	} else {
		src, err := s.searchSource.Source()
		if err != nil {
			return nil, err
		}
		body = src
	}
	res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
		Method:          "POST",
		Path:            path,
		Params:          params,
		Body:            body,
		MaxResponseSize: s.maxResponseSize,
	})
	if err != nil {
		return nil, err
	}

	// Return search results
	ret := new(SearchResult)
	if err := s.client.decoder.Decode(res.Body, ret); err != nil {
		return nil, err
	}
	return ret, nil
}
714759
func (m *MockEventInterface) Search(arg0 *runtime.Scheme, arg1 runtime.Object) (*v1.EventList, error) {
	ret := m.ctrl.Call(m, "Search", arg0, arg1)
	ret0, _ := ret[0].(*v1.EventList)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
291685
func (s *SearchResults) Next() (*SearchResults, error) {
	// get last timestamp
	var size = len(s.Posts)
	if size < 1 {
		return nil, NoNextPageError
	}
	lastPost := s.Posts[size-1].GetSelf()
	lastTs := lastPost.FeaturedTimestamp
	if lastTs < 1 {
		lastTs = lastPost.Timestamp
	}
	params := s.params
	params.Set("before", strconv.FormatUint(lastTs, 10))
	return TaggedSearch(s.client, params.Get("tag"), params)
}
434876
func Search(searchBy SearchKey, propertyName string) (*SearchResult, error) {
	req, err := client.NewJSONRequest(
		Config,
		"POST",
		"/papi/v1/search/find-by-value",
		map[string]string{(string)(searchBy): propertyName},
	)

	if err != nil {
		return nil, err
	}

	res, err := client.Do(Config, req)

	if client.IsError(res) {
		return nil, client.NewAPIError(res)
	}


	results := &SearchResult{}
	if err = client.BodyJSON(res, results); err != nil {
		return nil, err
	}

	if len(results.Versions.Items) == 0 {
		return nil, nil
	}

	return results, nil
}
814334
func (s MultiSimpleSearcher) Search(precise bool, terms ...string) (ComponentMatches, []error) {
	var errs []error
	componentMatches := ComponentMatches{}
	for _, searcher := range s {
		matches, err := searcher.Search(precise, terms...)
		if len(err) > 0 {
			errs = append(errs, err...)
			continue
		}
		componentMatches = append(componentMatches, matches...)
	}
	sort.Sort(ScoredComponentMatches(componentMatches))
	return componentMatches, errs
}
992630
func (r DockerClientSearcher) Search(precise bool, terms ...string) (ComponentMatches, []error) {
	componentMatches := ComponentMatches{}
	errs := []error{}
	for _, term := range terms {
		var (
			ref imageapi.DockerImageReference
			err error
		)
		switch term {
		case "__dockerimage_fail":
			errs = append(errs, fmt.Errorf("unable to find the specified docker image: %s", term))
			continue
		case "scratch":
			componentMatches = append(componentMatches, &ComponentMatch{
				Value: term,
				Score: 0.0,
				// we don't want to create an imagestream for "scratch", so treat
				// it as a local only image.
				LocalOnly: true,
				Virtual:   true,
			})
			return componentMatches, errs
		case "*":
			ref = imageapi.DockerImageReference{Name: term}
		default:
			ref, err = imageapi.ParseDockerImageReference(term)
			if err != nil {
				continue
			}
		}

		termMatches := ScoredComponentMatches{}

		// first look for the image in the remote docker registry
		if r.RegistrySearcher != nil {
			klog.V(4).Infof("checking remote registry for %q", ref.String())
			matches, err := r.RegistrySearcher.Search(precise, term)
			errs = append(errs, err...)

			for i := range matches {
				matches[i].LocalOnly = false
				klog.V(5).Infof("Found remote match %v", matches[i].Value)
			}
			termMatches = append(termMatches, matches...)
		}

		if r.Client == nil || reflect.ValueOf(r.Client).IsNil() {
			componentMatches = append(componentMatches, termMatches...)
			continue
		}

		// if we didn't find it exactly in a remote registry,
		// try to find it as a local-only image.
		if len(termMatches.Exact()) == 0 {
			klog.V(4).Infof("checking local Docker daemon for %q", ref.String())
			images, err := r.Client.ListImages(docker.ListImagesOptions{})
			if err != nil {
				errs = append(errs, err)
				continue
			}

			if len(ref.Tag) == 0 {
				ref.Tag = imageapi.DefaultImageTag
				term = fmt.Sprintf("%s:%s", term, imageapi.DefaultImageTag)
			}
			for _, image := range images {
				if tags := matchTag(image, term, ref.Registry, ref.Namespace, ref.Name, ref.Tag); len(tags) > 0 {
					for i := range tags {
						tags[i].LocalOnly = true
						klog.V(5).Infof("Found local docker image match %q with score %f", tags[i].Value, tags[i].Score)
					}
					termMatches = append(termMatches, tags...)
				}
			}
		}
		sort.Sort(termMatches)

		for i, match := range termMatches {
			if match.DockerImage != nil {
				continue
			}

			image, err := r.Client.InspectImage(match.Value)
			if err != nil {
				if err != docker.ErrNoSuchImage {
					errs = append(errs, err)
				}
				continue
			}
			dockerImage := &imageapi.DockerImage{}
			if err := legacyscheme.Scheme.Convert(image, dockerImage, nil); err != nil {
				errs = append(errs, err)
				continue
			}
			updated := &ComponentMatch{
				Value:       match.Value,
				Argument:    fmt.Sprintf("--docker-image=%q", match.Value),
				Name:        match.Value,
				Description: descriptionFor(dockerImage, match.Value, ref.Registry, ""),
				Score:       match.Score,
				DockerImage: dockerImage,
				ImageTag:    ref.Tag,
				Insecure:    r.Insecure,
				Meta:        map[string]string{"registry": ref.Registry},
				LocalOnly:   match.LocalOnly,
			}
			termMatches[i] = updated
		}

		componentMatches = append(componentMatches, termMatches...)
	}

	return componentMatches, errs
}