0
# Search and Filtering
1
2
Advanced job search capabilities with text queries, geographic filtering, compensation ranges, commute time calculations, and faceted search with histogram analytics for building sophisticated job search experiences. The search system supports natural language queries, structured filters, and machine learning-powered ranking.
3
4
## Capabilities
5
6
### Text Search
7
8
Performs natural language searches across job titles, descriptions, company names, and other textual content with intelligent query processing and ranking.
9
10
```python { .api }
11
class JobQuery:
12
"""Primary search query object for job searches."""
13
query: str = None # Free text search query (max 255 chars)
14
companies: List[str] = None # Filter by specific companies (max 20)
15
location_filters: List[LocationFilter] = None # Geographic filtering (max 5)
16
job_categories: List[JobCategory] = None # Filter by job categories
17
employment_types: List[EmploymentType] = None # Filter by employment types
18
compensation_filter: CompensationFilter = None # Salary range filtering
19
commute_filter: CommuteFilter = None # Commute time-based filtering
20
custom_attribute_filter: str = None # SQL-like custom field filtering
21
publish_time_range: TimestampRange = None # Filter by posting date
22
excluded_jobs: List[str] = None # Jobs to exclude from results
23
```
24
25
**Usage Example:**
26
27
```python
28
from google.cloud.talent import JobQuery, SearchJobsRequest
29
30
# Simple text search
31
query = JobQuery(query="python software engineer")
32
33
search_request = SearchJobsRequest(
34
parent="projects/my-project/tenants/my-tenant",
35
job_query=query
36
)
37
38
response = client.search_jobs(search_request)
39
```
40
41
### Geographic Filtering
42
43
Filters jobs based on location with support for addresses, coordinates, distance radius, and telecommute preferences.
44
45
```python { .api }
46
class LocationFilter:
47
"""Geographic search filtering with flexible location specification."""
48
address: str = None # Address or location name
49
region_code: str = None # CLDR country/region code (e.g., "US", "CA")
50
lat_lng: LatLng = None # Latitude/longitude coordinates
51
distance_in_miles: float = None # Search radius in miles
52
telecommute_preference: TelecommutePreference = None # Remote work filtering
53
54
class TelecommutePreference(Enum):
55
"""Telecommute filtering options."""
56
TELECOMMUTE_PREFERENCE_UNSPECIFIED = 0
57
TELECOMMUTE_EXCLUDED = 1 # Exclude remote jobs
58
TELECOMMUTE_ALLOWED = 2 # Include remote jobs
59
```
60
61
**Usage Example:**
62
63
```python
64
from google.cloud.talent import LocationFilter, LatLng
65
66
# Search by address with radius
67
location_filter = LocationFilter(
68
address="San Francisco, CA",
69
distance_in_miles=25.0
70
)
71
72
# Search by coordinates
73
location_filter_coords = LocationFilter(
74
lat_lng=LatLng(latitude=37.7749, longitude=-122.4194),
75
distance_in_miles=15.0
76
)
77
78
# Include remote jobs
79
location_filter_remote = LocationFilter(
80
address="San Francisco, CA",
81
distance_in_miles=50.0,
82
telecommute_preference=TelecommutePreference.TELECOMMUTE_ALLOWED
83
)
84
85
query = JobQuery(
86
query="software engineer",
87
location_filters=[location_filter, location_filter_remote]
88
)
89
```
90
91
### Compensation Filtering
92
93
Filters jobs based on salary ranges and compensation structures with support for different time units and compensation types.
94
95
```python { .api }
96
class CompensationFilter:
97
"""Salary and compensation filtering with flexible range specification."""
98
type_: FilterType = None # Filter type specification
99
units: List[CompensationUnit] = None # Time units for compensation
100
range_: CompensationRange = None # Min/max compensation range
101
include_jobs_with_unspecified_compensation: bool = None # Include jobs without salary info
102
103
class FilterType(Enum):
104
"""Compensation filter types."""
105
FILTER_TYPE_UNSPECIFIED = 0
106
UNIT_ONLY = 1 # Filter by compensation unit only
107
UNIT_AND_AMOUNT = 2 # Filter by unit and amount
108
ANNUALIZED_BASE_AMOUNT = 3 # Filter by annualized base salary
109
ANNUALIZED_TOTAL_AMOUNT = 4 # Filter by total compensation
110
111
class CompensationRange:
112
"""Compensation range specification."""
113
max_compensation: Money = None # Maximum compensation
114
min_compensation: Money = None # Minimum compensation
115
116
class Money:
117
"""Monetary amount specification."""
118
currency_code: str = None # ISO 4217 currency code (e.g., "USD")
119
units: int = None # Integer amount
120
nanos: int = None # Fractional amount (nano units)
121
```
122
123
**Usage Example:**
124
125
```python
126
from google.cloud.talent import CompensationFilter, CompensationRange, Money
127
128
# Filter by annual salary range
129
compensation_filter = CompensationFilter(
130
type_=CompensationFilter.FilterType.ANNUALIZED_BASE_AMOUNT,
131
range_=CompensationRange(
132
min_compensation=Money(currency_code="USD", units=80000),
133
max_compensation=Money(currency_code="USD", units=150000)
134
)
135
)
136
137
# Filter by hourly rate
138
hourly_filter = CompensationFilter(
139
type_=CompensationFilter.FilterType.UNIT_AND_AMOUNT,
140
units=[CompensationUnit.HOURLY],
141
range_=CompensationRange(
142
min_compensation=Money(currency_code="USD", units=50),
143
max_compensation=Money(currency_code="USD", units=100)
144
)
145
)
146
147
query = JobQuery(
148
query="contractor developer",
149
compensation_filter=hourly_filter
150
)
151
```
152
153
### Commute Time Filtering
154
155
Filters jobs based on commute time from a starting location using various transportation methods with traffic considerations.
156
157
```python { .api }
158
class CommuteFilter:
159
"""Commute time-based job filtering with transportation options."""
160
commute_method: CommuteMethod = None # Transportation method
161
start_coordinates: LatLng = None # Starting location coordinates
162
travel_duration: Duration = None # Max commute time (up to 1 hour)
163
allow_imprecise_addresses: bool = None # Allow approximate address matching
164
road_traffic: RoadTraffic = None # Traffic condition assumption
165
departure_time: TimeOfDay = None # Departure time for traffic calculation
166
167
class CommuteMethod(Enum):
168
"""Transportation methods for commute calculation."""
169
COMMUTE_METHOD_UNSPECIFIED = 0
170
DRIVING = 1 # Personal vehicle
171
TRANSIT = 2 # Public transportation
172
WALKING = 3 # Walking
173
CYCLING = 4 # Bicycle
174
TRANSIT_ACCESSIBLE = 5 # Accessible public transit
175
176
class RoadTraffic(Enum):
177
"""Traffic condition assumptions."""
178
ROAD_TRAFFIC_UNSPECIFIED = 0
179
TRAFFIC_FREE = 1 # No traffic delays
180
BUSY_HOUR = 2 # Peak traffic conditions
181
```
182
183
**Usage Example:**
184
185
```python
186
from google.cloud.talent import CommuteFilter, CommuteMethod, Duration, TimeOfDay
187
from datetime import timedelta
188
189
# 45-minute driving commute with traffic
190
commute_filter = CommuteFilter(
191
commute_method=CommuteMethod.DRIVING,
192
start_coordinates=LatLng(latitude=37.7749, longitude=-122.4194),
193
travel_duration=Duration(seconds=2700), # 45 minutes
194
road_traffic=RoadTraffic.BUSY_HOUR,
195
departure_time=TimeOfDay(hours=8, minutes=30) # 8:30 AM departure
196
)
197
198
# Public transit commute
199
transit_filter = CommuteFilter(
200
commute_method=CommuteMethod.TRANSIT,
201
start_coordinates=LatLng(latitude=37.7749, longitude=-122.4194),
202
travel_duration=Duration(seconds=3600) # 1 hour max
203
)
204
205
query = JobQuery(
206
query="software engineer",
207
commute_filter=commute_filter
208
)
209
```
210
211
### Custom Attribute Filtering
212
213
Filters jobs using custom attributes with SQL-like syntax for complex filtering scenarios.
214
215
```python { .api }
216
# Custom attribute filter examples
217
query = JobQuery(
218
query="data scientist",
219
custom_attribute_filter='(skills HAS "python" OR skills HAS "r") AND experience_level = "senior"'
220
)
221
222
# Numeric custom attributes
223
query_numeric = JobQuery(
224
query="sales",
225
custom_attribute_filter='quota_target >= 100000 AND territory = "west_coast"'
226
)
227
```
228
229
### Time-Based Filtering
230
231
Filters jobs based on posting date and other temporal criteria.
232
233
```python { .api }
234
from google.cloud.talent import TimestampRange
235
from google.protobuf.timestamp_pb2 import Timestamp
236
from datetime import datetime, timedelta
237
238
# Jobs posted in the last 7 days
239
now = datetime.utcnow()
240
week_ago = now - timedelta(days=7)
241
242
time_filter = TimestampRange(
243
start_time=Timestamp(seconds=int(week_ago.timestamp())),
244
end_time=Timestamp(seconds=int(now.timestamp()))
245
)
246
247
query = JobQuery(
248
query="python developer",
249
publish_time_range=time_filter
250
)
251
```
252
253
### Faceted Search and Histograms
254
255
Provides aggregated counts for various job attributes to build faceted search interfaces and analytics dashboards.
256
257
```python { .api }
258
class HistogramQuery:
259
"""Request for faceted search analytics."""
260
histogram_query: str = None # Facet field to aggregate
261
262
class HistogramQueryResult:
263
"""Histogram results with counts by facet values."""
264
histogram_query: str = None # Original query
265
histogram: Dict[str, int] = None # Facet value counts
266
```
267
268
**Usage Example:**
269
270
```python
271
from google.cloud.talent import HistogramQuery
272
273
search_request = SearchJobsRequest(
274
parent="projects/my-project/tenants/my-tenant",
275
job_query=JobQuery(query="software engineer"),
276
histogram_queries=[
277
HistogramQuery(histogram_query="employment_type"),
278
HistogramQuery(histogram_query="job_level"),
279
HistogramQuery(histogram_query="company_size"),
280
HistogramQuery(histogram_query="job_category")
281
]
282
)
283
284
response = client.search_jobs(search_request)
285
286
# Process histogram results for faceted search UI
287
for histogram_result in response.histogram_query_results:
288
print(f"Facet: {histogram_result.histogram_query}")
289
for facet_value, count in histogram_result.histogram.items():
290
print(f" {facet_value}: {count} jobs")
291
```
292
293
### Advanced Search Options
294
295
Configure search behavior with ranking, diversification, and result processing options.
296
297
```python { .api }
298
class SearchJobsRequest:
299
parent: str = None # Tenant resource name
300
search_mode: SearchMode = None # Search mode
301
job_query: JobQuery = None # Search query and filters
302
enable_broadening: bool = None # Enable query broadening for more results
303
histogram_queries: List[HistogramQuery] = None # Faceted search
304
job_view: JobView = None # Detail level in results
305
offset: int = None # Result offset for pagination
306
page_size: int = None # Page size (max 100 for search)
307
page_token: str = None # Pagination token
308
order_by: str = None # Sort order specification
309
diversification_level: DiversificationLevel = None # Result diversity
310
custom_ranking_info: CustomRankingInfo = None # Custom ranking factors
311
disable_keyword_match: bool = None # Disable keyword matching
312
313
class SearchMode(Enum):
314
"""Search mode options."""
315
SEARCH_MODE_UNSPECIFIED = 0
316
JOB_SEARCH = 1 # Standard job search
317
FEATURED_JOB_SEARCH = 2 # Featured jobs only
318
319
class DiversificationLevel(Enum):
320
"""Result diversification levels."""
321
DIVERSIFICATION_LEVEL_UNSPECIFIED = 0
322
DISABLED = 1 # No diversification
323
SIMPLE = 2 # Basic diversification
324
```
325
326
**Usage Example:**
327
328
```python
329
# Advanced search with custom ranking and diversification
330
search_request = SearchJobsRequest(
331
parent="projects/my-project/tenants/my-tenant",
332
search_mode=SearchMode.JOB_SEARCH,
333
job_query=JobQuery(
334
query="machine learning engineer",
335
location_filters=[LocationFilter(address="San Francisco, CA", distance_in_miles=30)]
336
),
337
enable_broadening=True,
338
diversification_level=DiversificationLevel.SIMPLE,
339
order_by="relevance desc",
340
job_view=JobView.JOB_VIEW_SMALL,
341
page_size=20
342
)
343
344
response = client.search_jobs(search_request)
345
```
346
347
## Search Response Processing
348
349
### Search Results Structure
350
351
```python { .api }
352
class SearchJobsResponse:
353
"""Complete search response with jobs, metadata, and analytics."""
354
matching_jobs: List[MatchingJob] = None # Jobs with match information
355
histogram_query_results: List[HistogramQueryResult] = None # Facet results
356
next_page_token: str = None # Pagination token
357
location_filters: List[Location] = None # Matched/corrected locations
358
estimated_total_size: int = None # Estimated total result count
359
total_size: int = None # Actual total result count (expensive)
360
metadata: ResponseMetadata = None # Response metadata
361
broadened_query_jobs_count: int = None # Count of broadened results
362
spell_correction: SpellCheckResult = None # Query spelling corrections
363
364
class MatchingJob:
365
"""Individual job result with match metadata."""
366
job: Job = None # Complete job object
367
job_summary: str = None # Highlighted summary
368
job_title_snippet: str = None # Highlighted title
369
search_text_snippet: str = None # Highlighted description excerpt
370
commute_info: CommuteInfo = None # Commute calculation results
371
```
372
373
### Processing Search Results
374
375
```python
376
# Process search results with highlighting and metadata
377
for matching_job in response.matching_jobs:
378
job = matching_job.job
379
380
print(f"Title: {matching_job.job_title_snippet or job.title}")
381
print(f"Company: {job.company}")
382
print(f"Summary: {matching_job.job_summary}")
383
384
# Display commute information if available
385
if matching_job.commute_info:
386
commute = matching_job.commute_info
387
print(f"Commute: {commute.travel_duration} via {commute.commute_method}")
388
389
print("---")
390
391
# Handle spelling corrections
392
if response.spell_correction:
393
if response.spell_correction.corrected_text:
394
print(f"Did you mean: {response.spell_correction.corrected_text}")
395
```
396
397
## Error Handling
398
399
Search operations can raise several types of exceptions:
400
401
```python
402
from google.api_core import exceptions
403
404
try:
405
response = client.search_jobs(search_request)
406
except exceptions.InvalidArgument as e:
407
# Handle invalid search parameters
408
print(f"Invalid search query: {e}")
409
except exceptions.PermissionDenied as e:
410
# Handle authorization errors
411
print(f"Access denied: {e}")
412
except exceptions.ResourceExhausted as e:
413
# Handle quota limits
414
print(f"Search quota exceeded: {e}")
415
```
416
417
Common error scenarios:
418
- **InvalidArgument**: Invalid query syntax, malformed filters, invalid page size
419
- **PermissionDenied**: Insufficient permissions for search operations
420
- **ResourceExhausted**: Search API quota limits exceeded
421
- **DeadlineExceeded**: Search timeout (use simpler queries or filters)
422
423
## Best Practices
424
425
1. **Query Optimization**: Use specific, relevant keywords and avoid overly broad queries
426
2. **Location Filtering**: Provide location context for better relevance and commute calculations
427
3. **Pagination**: Use appropriate page sizes (20-50 for user interfaces, larger for batch processing)
428
4. **Faceted Search**: Implement histogram queries for rich filtering UIs
429
5. **Performance**: Cache frequent searches and use appropriate job_view levels
430
6. **User Experience**: Implement query suggestions, spell correction, and broadening
431
7. **Geographic Accuracy**: Validate addresses and provide fallback location options
432
8. **Commute Calculations**: Consider traffic patterns and transportation availability in your region