class SearchService
SearchService is a class that exposes OData Service Operations for SharePoint Search functionality, providing methods to execute search queries, retrieve suggestions, export query logs, and manage search-related operations.
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/search/service.py
22 - 277
complex
Purpose
This class serves as a comprehensive interface to SharePoint's Search REST API, enabling operations such as executing search queries (GET and POST), retrieving auto-completions and suggestions, exporting query logs and popular queries, recording page clicks for analytics, and managing search center URLs. It inherits from Entity and is designed to work within a SharePoint context to perform search-related operations through OData service calls.
Source Code
class SearchService(Entity):
"""SearchService exposes OData Service Operations."""
def __init__(self, context):
super(SearchService, self).__init__(
context, ResourcePath("Microsoft.Office.Server.Search.REST.SearchService")
)
def export(self, user, start_time):
"""
The operation is used by the administrator to retrieve the query log entries,
issued after a specified date, for a specified user.
:param datetime.datetime start_time: The timestamp of the oldest query log entry returned.
:param str or User user: The name of the user or user object that issued the queries.
"""
return_type = ClientResult(self.context, str())
def _export(user_name):
"""
:type user_name: str
"""
payload = {"userName": user_name, "startTime": start_time.isoformat()}
qry = ServiceOperationQuery(
self, "export", None, payload, None, return_type
)
self.context.add_query(qry)
if isinstance(user, User):
def _user_loaded():
_export(user.user_principal_name)
user.ensure_property("UserPrincipalName", _user_loaded)
else:
_export(user)
return return_type
def export_manual_suggestions(self):
""" """
return_type = ClientResult(self.context, TenantCustomQuerySuggestions())
qry = ServiceOperationQuery(
self, "exportmanualsuggestions", None, None, None, return_type
)
self.context.add_query(qry)
return return_type
def export_popular_tenant_queries(self, count):
"""
This method is used to get a list of popular search queries executed on the tenant.
:param int count:
"""
return_type = ClientResult(
self.context, ClientValueCollection(PopularTenantQuery)
)
payload = {
"count": count,
}
qry = ServiceOperationQuery(
self, "exportpopulartenantqueries", None, payload, None, return_type
)
self.context.add_query(qry)
return return_type
def query(
self,
query_text,
source_id=None,
ranking_model_id=None,
start_row=None,
row_limit=None,
rows_per_page=None,
select_properties=None,
refinement_filters=None,
refiners=None,
sort_list=None,
trim_duplicates=None,
enable_query_rules=None,
enable_sorting=None,
**kwargs
):
"""The operation is used to retrieve search results by using the HTTP protocol with the GET method.
:param str query_text: The query text of the search query.
:param str source_id: Specifies the unique identifier for result source to use for executing the search query.
If no value is specified then the protocol server MUST use the id for the default result source.
:param str ranking_model_id: The GUID of the ranking model that SHOULD be used for this search query. If this
element is not present or a value is not specified, the protocol server MUST use the default ranking model,
according to protocol server configuration.
:param int start_row: A zero-based index of the first search result in the list of all search results the
protocol server returns. The StartRow value MUST be greater than or equal to zero.
:param int rows_per_page: The number of result items the protocol client displays per page. If this element is
set to an integer value less than 1, the value of the RowLimit element MUST be used as the default value.
:param int row_limit: The number of search results the protocol client wants to receive, starting at the index
specified in the StartRow element. The RowLimit value MUST be greater than or equal to zero.
:param list[str] select_properties: Specifies a property bag of key value pairs.
:param list[str] refinement_filters: The list of refinement tokens for drilldown into search results
:param list[str] refiners: Specifies a list of refiners
:param list[Sort] sort_list: Specifies the list of properties with which to sort the search results.
:param bool trim_duplicates: Specifies whether duplicates are removed by the protocol server before sorting,
selecting, and sending the search results.
:param bool enable_sorting: Specifies whether sorting of results is enabled or not.
MUST ignore the SortList specified if this value is set to false.
:param bool enable_query_rules: Specifies whether query rules are included when a search query is executed.
If the value is true, query rules are applied in the search query. If the value is false, query rules
MUST NOT be applied in the search query.
"""
params = {
"querytext": query_text,
"sourceId": source_id,
"rankingModelId": ranking_model_id,
"startRow": start_row,
"rowsPerPage": rows_per_page,
"trimDuplicates": trim_duplicates,
"rowLimit": row_limit,
"enableQueryRules": enable_query_rules,
"enableSorting": enable_sorting,
}
if refinement_filters:
params["refinementFilters"] = str(StringCollection(refinement_filters))
if sort_list:
params["sortList"] = str(StringCollection([str(s) for s in sort_list]))
if select_properties:
params["selectProperties"] = str(StringCollection(select_properties))
if refiners:
params["refiners"] = str(StringCollection(refiners))
params.update(**kwargs)
return_type = ClientResult(
self.context, SearchResult()
) # type: ClientResult[SearchResult]
qry = FunctionQuery(self, "query", params, return_type)
self.context.add_query(qry)
return return_type
def post_query(
self,
query_text,
select_properties=None,
trim_duplicates=None,
row_limit=None,
**kwargs
):
"""The operation is used to retrieve search results through the use of the HTTP protocol
with method type POST.
:param str query_text: The query text of the search query.
:param list[str] select_properties: Specifies a property bag of key value pairs.
:param bool trim_duplicates: Specifies whether duplicates are removed by the protocol server before sorting,
selecting, and sending the search results.
:param int row_limit: The number of search results the protocol client wants to receive, starting at the index
specified in the StartRow element. The RowLimit value MUST be greater than or equal to zero.
"""
return_type = ClientResult(
self.context, SearchResult()
) # type: ClientResult[SearchResult]
request = SearchRequest(
query_text=query_text,
select_properties=select_properties,
trim_duplicates=trim_duplicates,
row_limit=row_limit,
**kwargs
)
payload = {"request": request}
qry = ServiceOperationQuery(self, "postquery", None, payload, None, return_type)
self.context.add_query(qry)
return return_type
def record_page_click(self, page_info=None, click_type=None, block_type=None):
"""This operation is used by the protocol client to inform the protocol server that a user clicked a
query result on a page. When a click happens, the protocol client sends the details about the click
and the page impression for which the query result was clicked to the protocol server.
This operation MUST NOT be used if no query logging information is returned for a query.
Also this operation MUST NOT be used if a user clicks a query result for which query logging
information was not returned
:param str page_info: Specifies the information about the clicked page, the page impression.
:param str click_type: Type of clicks. If a particular query result is clicked then the click type returned
by the search service for this query result MUST be used. If "more" link is clicked then "ClickMore"
click type MUST be used.
:param str block_type: Type of query results in the page impression block
"""
payload = {
"pageInfo": page_info,
"clickType": click_type,
"blockType": block_type,
}
qry = ServiceOperationQuery(self, "RecordPageClick", None, payload)
self.context.add_query(qry)
return self
def search_center_url(self):
"""The operation is used to get the URI address of the search center by using the HTTP protocol
with the GET method. The operation returns the URI of the of the search center.
"""
return_type = ClientResult(self.context)
qry = ServiceOperationQuery(
self, "searchCenterUrl", None, None, None, return_type
)
self.context.add_query(qry)
return return_type
def results_page_address(self):
"""The operation is used to get the URI address of the result page by using the HTTP protocol
with the GET method. The operation returns the URI of the result page."""
return_type = ClientResult(self.context, str())
qry = ServiceOperationQuery(
self, "resultspageaddress", None, None, None, return_type
)
self.context.add_query(qry)
return return_type
def suggest(self, query_text):
"""
:param str query_text: The query text of the search query. If this element is not present or a value
is not specified, a default value of an empty string MUST be used, and the server MUST return a
FaultException<ExceptionDetail> message.
"""
return_type = ClientResult(self.context, QuerySuggestionResults())
payload = {"querytext": query_text}
qry = ServiceOperationQuery(self, "suggest", None, payload, None, return_type)
self.context.add_query(qry)
return return_type
def auto_completions(
self, query_text, sources=None, number_of_completions=None, cursor_position=None
):
"""
The operation is used to retrieve auto completion results by using the HTTP protocol with the GET method.
:param str query_text: The query text of the search query. If this element is not present or a value is not
specified, a default value of an empty string MUST be used, and the server MUST return
a FaultException<ExceptionDetail> message.
:param str sources: Specifies the sources that the protocol server SHOULD use when computing the result.
If NULL, the protocol server SHOULD use all of the sources for autocompletions. The value SHOULD be a
comma separated set of sources for autocompletions. The set of available sources the server SHOULD support
is "Tag", which MAY be compiled from the set of #tags applied to documents. If the sources value is not
a comma separated set of sources, or any of the source does not match "Tag", the server SHOULD return
completions from all available sources.
:param int number_of_completions: Specifies the maximum number query completion results in
GetQueryCompletionsResponse response message.
:param int cursor_position: Specifies the cursor position in the query text when this operation is sent
to the protocol server.
"""
return_type = ClientResult(self.context, QueryAutoCompletionResults())
payload = {
"querytext": query_text,
"sources": sources,
"numberOfCompletions": number_of_completions,
"cursorPosition": cursor_position,
}
qry = ServiceOperationQuery(
self, "autocompletions", None, payload, None, return_type
)
self.context.add_query(qry)
return return_type
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
Entity | - |
Parameter Details
context: The SharePoint client context object that provides the connection and authentication information needed to communicate with the SharePoint server. This context is used to execute queries and manage the communication lifecycle with the SharePoint REST API.
Return Value
Instantiation returns a SearchService object configured with the provided context and a ResourcePath pointing to 'Microsoft.Office.Server.Search.REST.SearchService'. Most methods return ClientResult objects that wrap the actual result data (SearchResult, QuerySuggestionResults, QueryAutoCompletionResults, etc.) which are populated asynchronously when queries are executed through the context.
Class Interface
Methods
__init__(self, context)
Purpose: Initializes the SearchService instance with a SharePoint context
Parameters:
context: The SharePoint client context object for API communication
Returns: None - constructor initializes the instance
export(self, user, start_time) -> ClientResult[str]
Purpose: Retrieves query log entries issued after a specified date for a specified user (admin operation)
Parameters:
user: The name of the user (str) or User object that issued the queriesstart_time: datetime.datetime object representing the timestamp of the oldest query log entry to return
Returns: ClientResult[str] containing the exported query log data
export_manual_suggestions(self) -> ClientResult[TenantCustomQuerySuggestions]
Purpose: Exports manually configured query suggestions for the tenant
Returns: ClientResult[TenantCustomQuerySuggestions] containing the manual suggestions
export_popular_tenant_queries(self, count) -> ClientResult[ClientValueCollection[PopularTenantQuery]]
Purpose: Retrieves a list of popular search queries executed on the tenant
Parameters:
count: int - the maximum number of popular queries to return
Returns: ClientResult containing a ClientValueCollection of PopularTenantQuery objects
query(self, query_text, source_id=None, ranking_model_id=None, start_row=None, row_limit=None, rows_per_page=None, select_properties=None, refinement_filters=None, refiners=None, sort_list=None, trim_duplicates=None, enable_query_rules=None, enable_sorting=None, **kwargs) -> ClientResult[SearchResult]
Purpose: Executes a search query using HTTP GET method with comprehensive search parameters
Parameters:
query_text: str - the search query textsource_id: str (optional) - unique identifier for result source, uses default if not specifiedranking_model_id: str (optional) - GUID of the ranking model to usestart_row: int (optional) - zero-based index of first result to returnrow_limit: int (optional) - number of results to returnrows_per_page: int (optional) - number of results per pageselect_properties: list[str] (optional) - properties to include in resultsrefinement_filters: list[str] (optional) - refinement tokens for drilldownrefiners: list[str] (optional) - list of refiners to applysort_list: list[Sort] (optional) - properties to sort results bytrim_duplicates: bool (optional) - whether to remove duplicatesenable_query_rules: bool (optional) - whether to apply query rulesenable_sorting: bool (optional) - whether sorting is enabled
Returns: ClientResult[SearchResult] containing the search results
post_query(self, query_text, select_properties=None, trim_duplicates=None, row_limit=None, **kwargs) -> ClientResult[SearchResult]
Purpose: Executes a search query using HTTP POST method, useful for complex queries
Parameters:
query_text: str - the search query textselect_properties: list[str] (optional) - properties to include in resultstrim_duplicates: bool (optional) - whether to remove duplicatesrow_limit: int (optional) - number of results to return
Returns: ClientResult[SearchResult] containing the search results
record_page_click(self, page_info=None, click_type=None, block_type=None) -> SearchService
Purpose: Records a user click on a search result for analytics purposes
Parameters:
page_info: str (optional) - information about the clicked page impressionclick_type: str (optional) - type of click (e.g., 'ClickMore')block_type: str (optional) - type of query results in the page impression block
Returns: self (SearchService) for method chaining
search_center_url(self) -> ClientResult
Purpose: Retrieves the URI address of the search center
Returns: ClientResult containing the search center URL
results_page_address(self) -> ClientResult[str]
Purpose: Retrieves the URI address of the search results page
Returns: ClientResult[str] containing the results page URL
suggest(self, query_text) -> ClientResult[QuerySuggestionResults]
Purpose: Retrieves query suggestions based on the provided query text
Parameters:
query_text: str - the partial query text to get suggestions for
Returns: ClientResult[QuerySuggestionResults] containing the query suggestions
auto_completions(self, query_text, sources=None, number_of_completions=None, cursor_position=None) -> ClientResult[QueryAutoCompletionResults]
Purpose: Retrieves auto-completion results for the query text
Parameters:
query_text: str - the partial query text to get completions forsources: str (optional) - comma-separated sources for completions (e.g., 'Tag')number_of_completions: int (optional) - maximum number of completions to returncursor_position: int (optional) - cursor position in the query text
Returns: ClientResult[QueryAutoCompletionResults] containing the auto-completion suggestions
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
context |
ClientContext | The SharePoint client context inherited from Entity base class, used for executing queries | instance |
resource_path |
ResourcePath | The OData resource path pointing to 'Microsoft.Office.Server.Search.REST.SearchService', inherited from Entity | instance |
Dependencies
office365datetime
Required Imports
from office365.runtime.client_result import ClientResult
from office365.runtime.client_value_collection import ClientValueCollection
from office365.runtime.paths.resource_path import ResourcePath
from office365.runtime.queries.function import FunctionQuery
from office365.runtime.queries.service_operation import ServiceOperationQuery
from office365.runtime.types.collections import StringCollection
from office365.sharepoint.entity import Entity
from office365.sharepoint.principal.users.user import User
from office365.sharepoint.search.query.auto_completion_results import QueryAutoCompletionResults
from office365.sharepoint.search.query.popular_tenant_query import PopularTenantQuery
from office365.sharepoint.search.query.sort.sort import Sort
from office365.sharepoint.search.query.suggestion_results import QuerySuggestionResults
from office365.sharepoint.search.query.tenant_custom_query_suggestions import TenantCustomQuerySuggestions
from office365.sharepoint.search.request import SearchRequest
from office365.sharepoint.search.result import SearchResult
import datetime
Usage Example
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.search.service import SearchService
import datetime
# Setup context
site_url = 'https://yourtenant.sharepoint.com/sites/yoursite'
credentials = UserCredential('username@domain.com', 'password')
ctx = ClientContext(site_url).with_credentials(credentials)
# Create SearchService instance
search_service = SearchService(ctx)
# Execute a simple search query
result = search_service.query(
query_text='document',
row_limit=10,
select_properties=['Title', 'Path', 'Author']
)
ctx.execute_query()
print(f'Total rows: {result.value.TotalRows}')
for row in result.value.PrimaryQueryResult.RelevantResults.Table.Rows:
print(row.Cells)
# Get query suggestions
suggestions = search_service.suggest('doc')
ctx.execute_query()
for suggestion in suggestions.value.Queries:
print(suggestion)
# Export query logs (admin only)
start_date = datetime.datetime(2024, 1, 1)
export_result = search_service.export('user@domain.com', start_date)
ctx.execute_query()
print(export_result.value)
# Get auto-completions
completions = search_service.auto_completions(
query_text='docu',
number_of_completions=5
)
ctx.execute_query()
for completion in completions.value.Suggestions:
print(completion)
Best Practices
- Always call ctx.execute_query() after adding queries to actually execute them and populate the ClientResult objects
- Use post_query() for complex queries with many parameters or when query URL might exceed length limits
- The export() method requires administrator privileges and should only be used by authorized users
- When using the User object parameter in export(), ensure the UserPrincipalName property is loaded before the query executes
- ClientResult objects are populated asynchronously - access their .value property only after ctx.execute_query() completes
- For pagination, use start_row and row_limit parameters together in the query() method
- The record_page_click() method should only be used when query logging information is available from a previous query
- When specifying select_properties, refiners, or refinement_filters, pass them as lists of strings
- For sorting results, create Sort objects and pass them in the sort_list parameter
- The context object must remain in scope for the lifetime of the SearchService instance
- Handle exceptions appropriately as network errors or authentication failures can occur during query execution
- Use trim_duplicates=True to remove duplicate results before sorting and selecting results
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class SearchRequest 63.9% similar
-
class NavigationService 62.7% similar
-
class Search 62.6% similar
-
class SearchEndpoints 61.6% similar
-
class QuerySuggestionResults 61.2% similar