or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-auth.mddirect-messages.mdfavorites.mdindex.mdlists.mdplaces.mdsearch.mdstreaming.mdtimelines.mdtweets.mdusers.md

search.mddocs/

0

# Search Functionality

1

2

Comprehensive search capabilities for tweets, users, and trending topics.

3

4

## Tweet Search

5

6

### Search API

7

8

Search for tweets using keywords, hashtags, users, and advanced operators.

9

10

```java { .api }

11

interface SearchResource {

12

/**

13

* Search for tweets matching query

14

* @param query Search query with parameters

15

* @return Search results with tweets and metadata

16

*/

17

QueryResult search(Query query) throws TwitterException;

18

}

19

```

20

21

**Usage Examples:**

22

23

```java

24

TwitterV1 v1 = twitter.v1();

25

26

// Simple text search

27

Query query = Query.of("Twitter API");

28

QueryResult result = v1.search().search(query);

29

30

for (Status tweet : result.getTweets()) {

31

System.out.println("@" + tweet.getUser().getScreenName() + ": " + tweet.getText());

32

}

33

34

// Advanced search with filters

35

Query advancedQuery = Query.of("java programming")

36

.lang("en")

37

.resultType(Query.ResultType.recent)

38

.count(100)

39

.since("2023-01-01")

40

.until("2023-12-31");

41

42

QueryResult advancedResult = v1.search().search(advancedQuery);

43

```

44

45

### Query Builder

46

47

Comprehensive query construction with filters and parameters.

48

49

```java { .api }

50

class Query {

51

/**

52

* Create search query with search terms

53

* @param query Search terms and operators

54

* @return Query builder instance

55

*/

56

static Query of(String query);

57

58

/**

59

* Set language filter

60

* @param lang Language code (e.g., "en", "es", "fr")

61

* @return Query with language filter

62

*/

63

Query lang(String lang);

64

65

/**

66

* Set locale for query

67

* @param locale Locale string

68

* @return Query with locale setting

69

*/

70

Query locale(String locale);

71

72

/**

73

* Set maximum tweet ID (tweets older than this)

74

* @param maxId Maximum tweet ID

75

* @return Query with max ID filter

76

*/

77

Query maxId(long maxId);

78

79

/**

80

* Set number of results per page

81

* @param count Number of results (max 100)

82

* @return Query with count setting

83

*/

84

Query count(int count);

85

86

/**

87

* Set since date (YYYY-MM-DD format)

88

* @param since Start date for search

89

* @return Query with since date filter

90

*/

91

Query since(String since);

92

93

/**

94

* Set minimum tweet ID (tweets newer than this)

95

* @param sinceId Minimum tweet ID

96

* @return Query with since ID filter

97

*/

98

Query sinceId(long sinceId);

99

100

/**

101

* Set geocode filter for location-based search

102

* @param geocode "latitude,longitude,radius" (e.g., "37.781157,-122.398720,1mi")

103

* @return Query with geocode filter

104

*/

105

Query geocode(String geocode);

106

107

/**

108

* Set until date (YYYY-MM-DD format)

109

* @param until End date for search

110

* @return Query with until date filter

111

*/

112

Query until(String until);

113

114

/**

115

* Set result type filter

116

* @param resultType Type of results to return

117

* @return Query with result type filter

118

*/

119

Query resultType(ResultType resultType);

120

121

/**

122

* Get current query string

123

*/

124

String getQuery();

125

126

/**

127

* Get current language setting

128

*/

129

String getLang();

130

131

/**

132

* Get current count setting

133

*/

134

int getCount();

135

136

/**

137

* Get current max ID setting

138

*/

139

long getMaxId();

140

141

/**

142

* Get current since ID setting

143

*/

144

long getSinceId();

145

146

/**

147

* Result type enumeration

148

*/

149

enum ResultType {

150

/** Return most recent tweets */

151

recent,

152

/** Return most popular tweets */

153

popular,

154

/** Return mix of recent and popular */

155

mixed

156

}

157

}

158

```

159

160

### Search Operators

161

162

Advanced search operators for precise query construction:

163

164

```java

165

// Exact phrase

166

Query.of("\"Twitter API\"");

167

168

// From specific user

169

Query.of("from:twitterapi");

170

171

// To specific user

172

Query.of("to:twitterapi");

173

174

// Mentioning user

175

Query.of("@twitterapi");

176

177

// Hashtags

178

Query.of("#TwitterAPI");

179

180

// URLs

181

Query.of("twitter.com");

182

183

// Positive sentiment

184

Query.of("Twitter :)");

185

186

// Negative sentiment

187

Query.of("Twitter :(");

188

189

// Question tweets

190

Query.of("Twitter ?");

191

192

// Retweets

193

Query.of("RT @twitterapi");

194

195

// Links

196

Query.of("Twitter filter:links");

197

198

// Images

199

Query.of("Twitter filter:images");

200

201

// Videos

202

Query.of("Twitter filter:videos");

203

204

// Media (images or videos)

205

Query.of("Twitter filter:media");

206

207

// Verified accounts only

208

Query.of("Twitter filter:verified");

209

210

// Exclude retweets

211

Query.of("Twitter -filter:retweets");

212

213

// Complex query combining operators

214

Query complexQuery = Query.of("(Twitter API OR \"Twitter4J\") from:twitterapi -filter:retweets filter:links")

215

.lang("en")

216

.resultType(Query.ResultType.recent);

217

```

218

219

## Search Results

220

221

### Query Result Object

222

223

Search response with tweets and pagination metadata.

224

225

```java { .api }

226

interface QueryResult extends TwitterResponse {

227

/**

228

* List of tweets matching search query

229

*/

230

List<Status> getTweets();

231

232

/**

233

* Whether there are more results available

234

*/

235

boolean hasNext();

236

237

/**

238

* Get next page of results

239

* @return Query for next page

240

*/

241

Query nextQuery();

242

243

/**

244

* Refresh search with same parameters

245

* @return Query for refresh

246

*/

247

Query refreshQuery();

248

249

/**

250

* Maximum tweet ID in results

251

*/

252

long getMaxId();

253

254

/**

255

* Minimum tweet ID in results

256

*/

257

long getSinceId();

258

259

/**

260

* Search completion time in seconds

261

*/

262

double getCompletedIn();

263

264

/**

265

* Number of tweets per page

266

*/

267

int getCount();

268

269

/**

270

* Search query string

271

*/

272

String getQuery();

273

}

274

```

275

276

**Pagination Example:**

277

278

```java

279

Query query = Query.of("Twitter API").count(100);

280

QueryResult result = v1.search().search(query);

281

282

// Process first page

283

for (Status tweet : result.getTweets()) {

284

processTweet(tweet);

285

}

286

287

// Get additional pages

288

while (result.hasNext()) {

289

Query nextQuery = result.nextQuery();

290

result = v1.search().search(nextQuery);

291

292

for (Status tweet : result.getTweets()) {

293

processTweet(tweet);

294

}

295

296

// Respect rate limits

297

RateLimitStatus rateLimit = result.getRateLimitStatus();

298

if (rateLimit.getRemaining() <= 1) {

299

Thread.sleep(rateLimit.getSecondsUntilReset() * 1000L);

300

}

301

}

302

```

303

304

## Trending Topics

305

306

### Trends API

307

308

Access trending topics by location.

309

310

```java { .api }

311

interface TrendsResources {

312

/**

313

* Get trending topics for a specific location

314

* @param woeid Where On Earth ID for location

315

* @return Trending topics for location

316

*/

317

Trends getPlaceTrends(int woeid) throws TwitterException;

318

319

/**

320

* Get available trend locations

321

* @return List of locations with trend data

322

*/

323

ResponseList<Location> getAvailableTrends() throws TwitterException;

324

325

/**

326

* Get closest trend locations to coordinates

327

* @param location Geographic coordinates

328

* @return List of nearby trend locations

329

*/

330

ResponseList<Location> getClosestTrends(GeoLocation location) throws TwitterException;

331

}

332

```

333

334

**Usage Examples:**

335

336

```java

337

// Get worldwide trends (WOEID = 1)

338

Trends worldTrends = v1.trends().getPlaceTrends(1);

339

for (Trend trend : worldTrends.getTrends()) {

340

System.out.println("#" + trend.getName() + " (" + trend.getTweetVolume() + " tweets)");

341

}

342

343

// Get trends for specific city (e.g., New York = 2459115)

344

Trends nyTrends = v1.trends().getPlaceTrends(2459115);

345

346

// Find available trend locations

347

ResponseList<Location> locations = v1.trends().getAvailableTrends();

348

for (Location loc : locations) {

349

System.out.println(loc.getName() + " (WOEID: " + loc.getWoeid() + ")");

350

}

351

352

// Find trends near coordinates

353

GeoLocation sanFrancisco = new GeoLocation(37.7749, -122.4194);

354

ResponseList<Location> nearbyLocations = v1.trends().getClosestTrends(sanFrancisco);

355

```

356

357

### Trends Data Models

358

359

```java { .api }

360

interface Trends extends TwitterResponse {

361

/**

362

* Array of trending topics

363

*/

364

Trend[] getTrends();

365

366

/**

367

* Timestamp when trends were created

368

*/

369

LocalDateTime getCreatedAt();

370

371

/**

372

* Timestamp when trends are valid until

373

*/

374

LocalDateTime getAsOf();

375

376

/**

377

* Location information for trends

378

*/

379

Location[] getLocations();

380

}

381

382

interface Trend {

383

/**

384

* Trend name/hashtag

385

*/

386

String getName();

387

388

/**

389

* Trend search URL

390

*/

391

String getUrl();

392

393

/**

394

* Promoted content URL (if promoted)

395

*/

396

String getPromotedContent();

397

398

/**

399

* Search query for this trend

400

*/

401

String getQuery();

402

403

/**

404

* Estimated tweet volume (null if unavailable)

405

*/

406

Integer getTweetVolume();

407

}

408

409

interface Location {

410

/**

411

* Location name

412

*/

413

String getName();

414

415

/**

416

* Where On Earth ID

417

*/

418

int getWoeid();

419

420

/**

421

* Country name

422

*/

423

String getCountryName();

424

425

/**

426

* Country code

427

*/

428

String getCountryCode();

429

430

/**

431

* Parent location ID

432

*/

433

int getParentId();

434

435

/**

436

* Location type

437

*/

438

int getPlaceType();

439

440

/**

441

* Location URL

442

*/

443

String getUrl();

444

}

445

```

446

447

## Advanced Search Patterns

448

449

### Real-time Search Monitoring

450

451

```java

452

public class SearchMonitor {

453

private final TwitterV1 v1;

454

private final String searchTerm;

455

private long lastSeenId = 1L;

456

457

public SearchMonitor(TwitterV1 v1, String searchTerm) {

458

this.v1 = v1;

459

this.searchTerm = searchTerm;

460

}

461

462

public List<Status> getNewTweets() throws TwitterException {

463

Query query = Query.of(searchTerm)

464

.sinceId(lastSeenId)

465

.count(100)

466

.resultType(Query.ResultType.recent);

467

468

QueryResult result = v1.search().search(query);

469

List<Status> newTweets = result.getTweets();

470

471

if (!newTweets.isEmpty()) {

472

lastSeenId = newTweets.get(0).getId();

473

}

474

475

return newTweets;

476

}

477

}

478

```

479

480

### Historical Search with Date Ranges

481

482

```java

483

public class HistoricalSearch {

484

485

public List<Status> searchDateRange(TwitterV1 v1, String query,

486

String startDate, String endDate) throws TwitterException {

487

List<Status> allTweets = new ArrayList<>();

488

489

Query searchQuery = Query.of(query)

490

.since(startDate)

491

.until(endDate)

492

.count(100)

493

.resultType(Query.ResultType.recent);

494

495

QueryResult result = v1.search().search(searchQuery);

496

allTweets.addAll(result.getTweets());

497

498

// Paginate through all results

499

while (result.hasNext()) {

500

result = v1.search().search(result.nextQuery());

501

allTweets.addAll(result.getTweets());

502

503

// Rate limit handling

504

RateLimitStatus rateLimit = result.getRateLimitStatus();

505

if (rateLimit.getRemaining() <= 1) {

506

try {

507

Thread.sleep(rateLimit.getSecondsUntilReset() * 1000L);

508

} catch (InterruptedException e) {

509

Thread.currentThread().interrupt();

510

break;

511

}

512

}

513

}

514

515

return allTweets;

516

}

517

}

518

```

519

520

### Search Analytics

521

522

```java

523

public class SearchAnalytics {

524

525

public SearchStats analyzeSearchResults(QueryResult result) {

526

List<Status> tweets = result.getTweets();

527

528

SearchStats stats = new SearchStats();

529

stats.totalTweets = tweets.size();

530

stats.retweetCount = (int) tweets.stream().filter(Status::isRetweet).count();

531

stats.originalTweetCount = stats.totalTweets - stats.retweetCount;

532

533

stats.averageRetweetCount = tweets.stream()

534

.mapToInt(Status::getRetweetCount)

535

.average().orElse(0.0);

536

537

stats.averageFavoriteCount = tweets.stream()

538

.mapToInt(Status::getFavoriteCount)

539

.average().orElse(0.0);

540

541

stats.topHashtags = tweets.stream()

542

.flatMap(tweet -> Arrays.stream(tweet.getHashtagEntities()))

543

.collect(Collectors.groupingBy(

544

HashtagEntity::getText,

545

Collectors.counting()

546

))

547

.entrySet().stream()

548

.sorted(Map.Entry.<String, Long>comparingByValue().reversed())

549

.limit(10)

550

.collect(Collectors.toMap(

551

Map.Entry::getKey,

552

Map.Entry::getValue,

553

(e1, e2) -> e1,

554

LinkedHashMap::new

555

));

556

557

return stats;

558

}

559

560

public static class SearchStats {

561

public int totalTweets;

562

public int retweetCount;

563

public int originalTweetCount;

564

public double averageRetweetCount;

565

public double averageFavoriteCount;

566

public Map<String, Long> topHashtags;

567

}

568

}

569

570

## Additional Utility Resources

571

572

### Saved Searches Management

573

574

Manage saved search queries for quick access to frequently used searches.

575

576

```java { .api }

577

interface SavedSearchesResources {

578

/**

579

* Get list of saved searches for authenticated user

580

* @return List of saved search queries

581

*/

582

ResponseList<SavedSearch> getSavedSearches() throws TwitterException;

583

584

/**

585

* Get details of a specific saved search

586

* @param id Saved search ID

587

* @return Saved search details

588

*/

589

SavedSearch showSavedSearch(long id) throws TwitterException;

590

591

/**

592

* Create a new saved search

593

* @param query Search query to save

594

* @return Created saved search

595

*/

596

SavedSearch createSavedSearch(String query) throws TwitterException;

597

598

/**

599

* Delete a saved search

600

* @param id Saved search ID to delete

601

* @return Deleted saved search

602

*/

603

SavedSearch destroySavedSearch(long id) throws TwitterException;

604

}

605

606

interface SavedSearch extends TwitterResponse {

607

/**

608

* Saved search unique identifier

609

*/

610

long getId();

611

612

/**

613

* Search query string

614

*/

615

String getQuery();

616

617

/**

618

* Display name for the saved search

619

*/

620

String getName();

621

622

/**

623

* Position/order of the saved search

624

*/

625

int getPosition();

626

627

/**

628

* Creation timestamp

629

*/

630

LocalDateTime getCreatedAt();

631

}

632

```

633

634

**Usage Examples:**

635

636

```java

637

TwitterV1 v1 = twitter.v1();

638

639

// Get all saved searches

640

ResponseList<SavedSearch> savedSearches = v1.savedSearches().getSavedSearches();

641

for (SavedSearch search : savedSearches) {

642

System.out.println(search.getName() + ": " + search.getQuery());

643

}

644

645

// Create new saved search

646

SavedSearch newSearch = v1.savedSearches().createSavedSearch("Twitter API");

647

System.out.println("Created saved search: " + newSearch.getId());

648

649

// Delete saved search

650

SavedSearch deleted = v1.savedSearches().destroySavedSearch(newSearch.getId());

651

```

652

653

### Spam Reporting

654

655

Report spam and block abusive users.

656

657

```java { .api }

658

interface SpamReportingResource {

659

/**

660

* Report user as spam and block them

661

* @param screenName Screen name of user to report

662

* @return Reported and blocked user

663

*/

664

User reportSpam(String screenName) throws TwitterException;

665

666

/**

667

* Report user as spam and block them by user ID

668

* @param userId User ID to report

669

* @return Reported and blocked user

670

*/

671

User reportSpam(long userId) throws TwitterException;

672

}

673

```

674

675

**Usage Examples:**

676

677

```java

678

// Report spam user by screen name

679

User reportedUser = v1.spamReporting().reportSpam("spamaccount");

680

System.out.println("Reported and blocked: @" + reportedUser.getScreenName());

681

682

// Report spam user by ID

683

User reportedById = v1.spamReporting().reportSpam(123456789L);

684

```

685

686

### API Help and Configuration

687

688

Access API configuration information and help resources.

689

690

```java { .api }

691

interface HelpResources {

692

/**

693

* Get supported languages for Twitter

694

* @return List of supported language codes and names

695

*/

696

ResponseList<Language> getLanguages() throws TwitterException;

697

698

/**

699

* Get rate limit status for all endpoints

700

* @return Map of endpoint families to rate limit status

701

*/

702

Map<String, RateLimitStatus> getRateLimitStatus() throws TwitterException;

703

704

/**

705

* Get rate limit status for specific endpoint families

706

* @param resources Endpoint family names (e.g., "search", "statuses", "users")

707

* @return Map of specified families to rate limit status

708

*/

709

Map<String, RateLimitStatus> getRateLimitStatus(String... resources) throws TwitterException;

710

711

/**

712

* Get Twitter API configuration settings

713

* @return API configuration parameters

714

*/

715

TwitterAPIConfiguration getAPIConfiguration() throws TwitterException;

716

717

/**

718

* Get privacy policy information

719

* @return Privacy policy details

720

*/

721

String getPrivacyPolicy() throws TwitterException;

722

723

/**

724

* Get terms of service information

725

* @return Terms of service details

726

*/

727

String getTermsOfService() throws TwitterException;

728

}

729

730

interface Language {

731

/**

732

* Language code (e.g., "en", "es", "fr")

733

*/

734

String getCode();

735

736

/**

737

* Language name in native script

738

*/

739

String getName();

740

741

/**

742

* Language name in English

743

*/

744

String getLocalName();

745

746

/**

747

* Whether language is right-to-left

748

*/

749

boolean isRightToLeft();

750

}

751

752

interface TwitterAPIConfiguration {

753

/**

754

* Maximum characters allowed in tweet

755

*/

756

int getCharactersReservedPerMedia();

757

758

/**

759

* Maximum length of direct messages

760

*/

761

int getDmTextCharacterLimit();

762

763

/**

764

* Photo size configurations

765

*/

766

Map<String, PhotoSize> getPhotoSizes();

767

768

/**

769

* Maximum photo size in bytes

770

*/

771

long getPhotoSizeLimit();

772

773

/**

774

* Short URL length

775

*/

776

int getShortUrlLength();

777

778

/**

779

* HTTPS short URL length

780

*/

781

int getShortUrlLengthHttps();

782

}

783

```

784

785

**Usage Examples:**

786

787

```java

788

// Get supported languages

789

ResponseList<Language> languages = v1.help().getLanguages();

790

for (Language lang : languages) {

791

System.out.println(lang.getCode() + ": " + lang.getName());

792

}

793

794

// Check rate limits for specific endpoints

795

Map<String, RateLimitStatus> rateLimits = v1.help().getRateLimitStatus("search", "statuses");

796

for (Map.Entry<String, RateLimitStatus> entry : rateLimits.entrySet()) {

797

RateLimitStatus status = entry.getValue();

798

System.out.println(entry.getKey() + ": " + status.getRemaining() + "/" + status.getLimit());

799

}

800

801

// Get API configuration

802

TwitterAPIConfiguration config = v1.help().getAPIConfiguration();

803

System.out.println("Tweet character limit: " + config.getCharactersReservedPerMedia());

804

System.out.println("DM character limit: " + config.getDmTextCharacterLimit());

805

```