### Get BLAST Server Information with blast.RequestInfo Source: https://context7.com/biogo/ncbi/llms.txt Queries the NCBI server to retrieve current service status and configuration information. ```go package main import ( "fmt" "log" "github.com/biogo/ncbi/blast" ) const ( tool = "myapp" email = "user@example.com" ) func main() { info, err := blast.RequestInfo("", tool, email) if err != nil { log.Fatal(err) } fmt.Printf("BLAST Server Status:\n") for _, status := range info.Status { fmt.Printf(" %s: %s\n", status.Name, status.Value) } } ``` -------------------------------- ### Get Database Information Source: https://context7.com/biogo/ncbi/llms.txt Retrieves metadata for Entrez databases. Providing an empty string lists all databases, while a specific name returns detailed database information. ```go package main import ( "fmt" "log" "github.com/biogo/ncbi/entrez" ) const ( tool = "myapp" email = "user@example.com" ) func main() { // List all available databases info, err := entrez.DoInfo("", tool, email) if err != nil { log.Fatal(err) } fmt.Println("Available databases:") for _, db := range info.DbList { fmt.Printf(" - %s\n", db) } // Get detailed info for protein database proteinInfo, err := entrez.DoInfo("protein", tool, email) if err != nil { log.Fatal(err) } if proteinInfo.DbInfo != nil { fmt.Printf("\nProtein database: %s\n", proteinInfo.DbInfo.Description) fmt.Printf("Record count: %d\n", proteinInfo.DbInfo.Count) fmt.Printf("Last updated: %s\n", proteinInfo.DbInfo.LastUpdate) } } ``` -------------------------------- ### Get Document Summaries with entrez.DoSummary Source: https://context7.com/biogo/ncbi/llms.txt Retrieves document summaries (DocSums) for a list of UIDs without downloading full records. ```go package main import ( "fmt" "log" "github.com/biogo/ncbi/entrez" ) const ( tool = "myapp" email = "user@example.com" ) func main() { // Get summaries for specific protein UIDs summary, err := entrez.DoSummary("protein", nil, tool, email, nil, 15718680, 15718681, 15718682) if err != nil { log.Fatal(err) } fmt.Printf("Retrieved %d document summaries from %s\n", len(summary.Documents), summary.Database) for _, doc := range summary.Documents { fmt.Printf("\nUID: %d\n", doc.Id) for _, item := range doc.Items { fmt.Printf(" %s (%s): %v\n", item.Name, item.Type, item.Value) } } } ``` -------------------------------- ### Fetch Sequences from NCBI Entrez Source: https://github.com/biogo/ncbi/blob/master/README.md This example demonstrates how to retrieve a large set of sequences from NCBI using the Entrez Utility Programs. It handles multiple retries for fetching data and writes the output to a specified file or stdout. Ensure you provide a valid email address and query. ```go package main import ( "bytes" "flag" "io" "log" "os" "github.com/biogo/ncbi" "github.com/biogo/ncbi/entrez" ) const ( tool = "entrez.example" ) var ( clQuery = flag.String("query", "", "query specifies the search query for record retrieval (required).") db = flag.String("db", "protein", "db specifies the database to search") ретtype = flag.String("rettype", "fasta", "rettype specifies the format of the returned data.") retmax = flag.Int("retmax", 500, "retmax specifies the number of records to be retrieved per request.") out = flag.String("out", "", "out specifies destination of the returned data (default to stdout).") email = flag.String("email", "", "email specifies the email address to be sent to the server (required).") retries = flag.Int("retry", 5, "retry specifies the number of attempts to retrieve the data.") help = flag.Bool("help", false, "help prints this message.") ) func main() { ncbi.SetTimeout(0) flag.Parse() if *help { flag.Usage() os.Exit(0) } if *email == "" || *clQuery == "" { flag.Usage() os.Exit(1) } h := entrez.History{} s, err := entrez.DoSearch(*db, *clQuery, nil, &h, tool, *email) if err != nil { log.Printf("error: %v\n", err) os.Exit(1) } log.Printf("will retrieve %d records.\n", s.Count) var of *os.File if *out == "" { of = os.Stdout } else { of, err = os.Create(*out) if err != nil { log.Printf("error: %v\n", err) os.Exit(1) } defer of.Close() } var ( buf = &bytes.Buffer{} p = &entrez.Parameters{RetMax: *retmax, RetType: *rettype, RetMode: "text"} bn, n int64 ) for p.RetStart = 0; p.RetStart < s.Count; p.RetStart += p.RetMax { log.Printf("attempting to retrieve %d records starting from %d with %d retries.\n", p.RetMax, p.RetStart, *retries) var t int for t = 0; t < *retries; t++ { buf.Reset() var ( r io.ReadCloser _bn int64 ) r, err = entrez.Fetch(*db, p, tool, *email, &h) if err != nil { if r != nil { r.Close() } log.Printf("failed to retrieve on attempt %d... error: %v ... retrying.\n", t, err) continue } _bn, err = io.Copy(buf, r) bn += _bn r.Close() if err == nil { break } log.Printf("failed to buffer on attempt %d... error: %v ... retrying.\n", t, err) } if err != nil { os.Exit(1) } log.Printf("retrieved records with %d retries... writing out.\n", t) _n, err := io.Copy(of, buf) n += _n if err != nil { log.Printf("Error: %v\n", err) os.Exit(1) } } if bn != n { log.Printf("writethrough mismatch: %d != %d\n", bn, n) } } ``` -------------------------------- ### GET /blast/info - Get BLAST Server Information Source: https://context7.com/biogo/ncbi/llms.txt Retrieves current information about the NCBI BLAST services, including available databases, programs, and server status. ```APIDOC ## GET /blast/info ### Description Retrieves current information about the NCBI BLAST services, including available databases, programs, and server status. ### Method GET ### Endpoint /blast/info ### Parameters #### Query Parameters - **tool** (string) - Required - User identification string. - **email** (string) - Required - User's email address. ### Response #### Success Response (200) - **Status** (array) - An array of objects, each describing the status of a BLAST service component. - **Name** (string) - The name of the service component. - **Value** (string) - The status of the component (e.g., "running", "available"). #### Response Example ```json { "Status": [ { "Name": "blastp", "Value": "running" }, { "Name": "blastn", "Value": "available" } ] } ``` ``` -------------------------------- ### GET /blast/rid/getoutput - Retrieve BLAST Results Source: https://context7.com/biogo/ncbi/llms.txt Retrieves the complete BLAST output for a completed search job. Results can be fetched in a structured format or as raw data. ```APIDOC ## GET /blast/{rid}/getoutput ### Description Retrieves the complete BLAST output for a completed search job. Results can be fetched in a structured format or as raw data. ### Method GET ### Endpoint /blast/{rid}/getoutput ### Parameters #### Path Parameters - **rid** (string) - Required - The Request ID of the BLAST job. #### Query Parameters - **tool** (string) - Required - User identification string. - **email** (string) - Required - User's email address. - **getParams** (object) - Optional - Parameters for formatting the output. - **Alignments** (integer) - Optional - The number of alignments to return. - **Descriptions** (integer) - Optional - The number of descriptions to return. ### Request Example ```json { "getParams": { "Alignments": 10, "Descriptions": 10 } } ``` ### Response #### Success Response (200) - **Program** (string) - The BLAST program used. - **Database** (string) - The database searched. - **QueryDef** (string) - The definition line of the query sequence. - **QueryLen** (integer) - The length of the query sequence. - **Iterations** (array) - An array of search iterations, each containing hits. - **Hits** (array) - An array of alignment hits. - **Def** (string) - Definition of the hit. - **Accession** (string) - Accession number of the hit. - **Len** (integer) - Length of the hit sequence. - **Hsps** (array) - High-scoring Segment Pairs. - **EValue** (float) - Expect value of the HSP. - **BitScore** (float) - Bit score of the HSP. - **QueryFrom** (integer) - Start position in the query sequence. - **QueryTo** (integer) - End position in the query sequence. - **HitFrom** (integer) - Start position in the hit sequence. - **HitTo** (integer) - End position in the hit sequence. - **HspIdentity** (integer) - Number of identical residues. - **AlignLen** (integer) - Length of the alignment. #### Response Example ```json { "Program": "blastp", "Database": "swissprot", "QueryDef": "test", "QueryLen": 30, "Iterations": [ { "N": 1, "Hits": [ { "Def": "Example protein", "Accession": "P12345", "Len": 100, "Hsps": [ { "EValue": 1e-5, "BitScore": 50.5, "QueryFrom": 1, "QueryTo": 30, "HitFrom": 1, "HitTo": 30, "HspIdentity": 25, "AlignLen": 30 } ] } ] } ] } ``` ``` -------------------------------- ### entrez.DoInfo - Get Database Information Source: https://context7.com/biogo/ncbi/llms.txt Retrieves information about NCBI Entrez databases. It can return a list of all databases or detailed information about a specific database. ```APIDOC ## entrez.DoInfo - Get Database Information ### Description Retrieves information about NCBI Entrez databases. Returns a list of all databases if no specific database is provided, or detailed information about a specific database including available fields and links. ### Method func DoInfo(db, tool, email string) (*Info, error) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "log" "github.com/biogo/ncbi/entrez" ) const ( tool = "myapp" email = "user@example.com" ) func main() { // List all available databases info, err := entrez.DoInfo("", tool, email) if err != nil { log.Fatal(err) } fmt.Println("Available databases:") for _, db := range info.DbList { fmt.Printf(" - %s\n", db) } // Get detailed info for protein database proteinInfo, err := entrez.DoInfo("protein", tool, email) if err != nil { log.Fatal(err) } if proteinInfo.DbInfo != nil { fmt.Printf("\nProtein database: %s\n", proteinInfo.DbInfo.Description) fmt.Printf("Record count: %d\n", proteinInfo.DbInfo.Count) fmt.Printf("Last updated: %s\n", proteinInfo.DbInfo.LastUpdate) } } ``` ### Response #### Success Response (200) - **DbList** ([]string) - A list of available Entrez database names. - **DbInfo** (*DbInfo) - Detailed information about a specific database. - **DbInfo.Description** (string) - Description of the database. - **DbInfo.Count** (int) - Number of records in the database. - **DbInfo.LastUpdate** (string) - The last update timestamp of the database. #### Response Example ```json { "DbList": ["pubmed", "protein", "genome", ...], "DbInfo": { "Description": "Protein sequences", "Count": 123456789, "LastUpdate": "2023-10-27 10:00:00" } } ``` ### Error Handling - **error** - An error object if the request fails. ``` -------------------------------- ### Entrez DoSpell - Get Spelling Suggestions Source: https://context7.com/biogo/ncbi/llms.txt Retrieves spelling suggestions for a potentially misspelled search term within a specified Entrez database. Requires tool name and email for identification. ```go package main import ( "fmt" "log" "github.com/biogo/ncbi/entrez" ) const ( tool = "myapp" email = "user@example.com" ) func main() { // Get spelling suggestion for a misspelled term spell, err := entrez.DoSpell("pubmed", "asthmaa", tool, email) if err != nil { log.Fatal(err) } fmt.Printf("Original query: %s\n", spell.Query) fmt.Printf("Corrected query: %s\n", spell.CorrectedQuery) } ``` -------------------------------- ### GET /blast/rid/searchinfo - Check BLAST Job Status Source: https://context7.com/biogo/ncbi/llms.txt Retrieves the current status of a BLAST search job using its RID. This endpoint is used to poll for job completion. ```APIDOC ## GET /blast/{rid}/searchinfo ### Description Retrieves the current status of a BLAST search job using its RID. This endpoint is used to poll for job completion. ### Method GET ### Endpoint /blast/{rid}/searchinfo ### Parameters #### Path Parameters - **rid** (string) - Required - The Request ID of the BLAST job. #### Query Parameters - **tool** (string) - Required - User identification string. - **email** (string) - Required - User's email address. ### Response #### Success Response (200) - **Status** (string) - The current status of the job (e.g., "RUNNING", "READY", "FAILED"). - **HaveHits** (boolean) - Indicates if the search has produced any results. #### Response Example ```json { "Status": "READY", "HaveHits": true } ``` ``` -------------------------------- ### Create Rate Limiter Source: https://context7.com/biogo/ncbi/llms.txt Initializes a thread-safe rate limiter to manage request frequency. The Wait method blocks execution until the next request is permitted. ```go package main import ( "fmt" "time" "github.com/biogo/ncbi" ) func main() { // Create a limiter that allows one request per second limiter := ncbi.NewLimiter(time.Second) for i := 0; i < 5; i++ { limiter.Wait() // Blocks until safe to proceed fmt.Printf("Request %d at %v\n", i, time.Now()) } } ``` -------------------------------- ### Create RID from Existing Request with blast.NewRid Source: https://context7.com/biogo/ncbi/llms.txt Initializes a RID object from a known request ID string to check status or fetch results for previously submitted searches. ```go package main import ( "fmt" "log" "github.com/biogo/ncbi/blast" ) const ( tool = "myapp" email = "user@example.com" ) func main() { // Use a previously obtained RID (valid for ~24 hours) existingRID := "ABCD1234567890" rid := blast.NewRid(existingRID) fmt.Printf("Using RID: %s\n", rid) // Check status and retrieve results if ready info, err := rid.SearchInfo(tool, email) if err != nil { log.Fatal(err) } if info.Status == "READY" && info.HaveHits { output, err := rid.GetOutput(nil, tool, email) if err != nil { log.Fatal(err) } fmt.Printf("Retrieved %d iterations\n", len(output.Iterations)) } } ``` -------------------------------- ### Batch Sequence Retrieval with Retry Logic Source: https://context7.com/biogo/ncbi/llms.txt Searches Entrez for sequences and fetches them in batches, incorporating retry logic for robustness. Requires 'protein' database and 'hemoglobin AND human[organism]' query. Outputs to 'sequences.fasta'. ```go package main import ( "bytes" "fmt" "io" "log" "os" "github.com/biogo/ncbi" "github.com/biogo/ncbi/entrez" ) const ( tool = "batch_fetcher" email = "user@example.com" ) func main() { ncbi.SetTimeout(0) // Search for sequences h := entrez.History{} search, err := entrez.DoSearch("protein", "hemoglobin AND human[organism]", nil, &h, tool, email) if err != nil { log.Fatal(err) } fmt.Printf("Found %d records\n", search.Count) // Fetch in batches batchSize := 100 retries := 3 params := &entrez.Parameters{ RetType: "fasta", RetMode: "text", RetMax: batchSize, } outFile, err := os.Create("sequences.fasta") if err != nil { log.Fatal(err) } defer outFile.Close() for params.RetStart = 0; params.RetStart < search.Count; params.RetStart += batchSize { var reader io.ReadCloser for attempt := 0; attempt < retries; attempt++ { reader, err = entrez.Fetch("protein", params, tool, email, &h) if err == nil { break } log.Printf("Attempt %d failed: %v\n", attempt+1, err) } if err != nil { log.Fatal(err) } buf := new(bytes.Buffer) io.Copy(buf, reader) reader.Close() outFile.Write(buf.Bytes()) fmt.Printf("Fetched records %d-%d\n", params.RetStart, params.RetStart+batchSize) } fmt.Println("Download complete!") } ``` -------------------------------- ### Retrieve BLAST Results with blast.Rid.GetOutput Source: https://context7.com/biogo/ncbi/llms.txt Submits a BLAST search and polls for completion before fetching structured results. Requires a valid tool name and email address for NCBI API compliance. ```go package main import ( "fmt" "log" "github.com/biogo/ncbi/blast" ) const ( tool = "myapp" email = "user@example.com" ) func main() { query := ">test\nMKTAYIAKQRQISFVKSHFSRQLEEALLYTI" putParams := &blast.PutParameters{ Program: "blastp", Database: "swissprot", HitListSize: 10, } rid, err := blast.Put(query, putParams, tool, email) if err != nil { log.Fatal(err) } // Wait for completion var info *blast.SearchInfo for { info, err = rid.SearchInfo(tool, email) if err != nil { log.Fatal(err) } if info.Status == "READY" { break } if info.Status != "WAITING" { log.Fatalf("Unexpected status: %s", info.Status) } } // Get results with parameters getParams := &blast.GetParameters{ Alignments: 10, Descriptions: 10, } output, err := rid.GetOutput(getParams, tool, email) if err != nil { log.Fatal(err) } // Process results fmt.Printf("Program: %s\n", output.Program) fmt.Printf("Database: %s\n", output.Database) fmt.Printf("Query: %s (%d bp)\n", output.QueryDef, output.QueryLen) for _, iteration := range output.Iterations { fmt.Printf("\nIteration %d:\n", iteration.N) for _, hit := range iteration.Hits { fmt.Printf(" Hit: %s\n", hit.Def) fmt.Printf(" Accession: %s, Length: %d\n", hit.Accession, hit.Len) for _, hsp := range hit.Hsps { fmt.Printf(" E-value: %.2e, Bit Score: %.1f\n", hsp.EValue, hsp.BitScore) fmt.Printf(" Query: %d-%d\n", hsp.QueryFrom, hsp.QueryTo) fmt.Printf(" Subject: %d-%d\n", hsp.HitFrom, hsp.HitTo) if hsp.HspIdentity != nil && hsp.AlignLen != nil { pctIdent := float64(*hsp.HspIdentity) / float64(*hsp.AlignLen) * 100 fmt.Printf(" Identity: %d/%d (%.1f%%)\n", *hsp.HspIdentity, *hsp.AlignLen, pctIdent) } } } if iteration.Statistics != nil { fmt.Printf(" Database: %d sequences, %d letters\n", iteration.Statistics.DbNum, iteration.Statistics.DbLen) } } } ``` -------------------------------- ### Configure HTTP Client Timeout Source: https://context7.com/biogo/ncbi/llms.txt Sets the global timeout duration for HTTP requests. Use 0 to disable the timeout for large data transfers. ```go package main import ( "time" "github.com/biogo/ncbi" ) func main() { // Disable timeout for large downloads ncbi.SetTimeout(0) // Or set a custom timeout of 30 seconds ncbi.SetTimeout(30 * time.Second) } ``` -------------------------------- ### Upload UIDs to History Server with entrez.DoPost Source: https://context7.com/biogo/ncbi/llms.txt Posts a list of UIDs to the Entrez history server for use in subsequent queries. ```go package main import ( "fmt" "log" "github.com/biogo/ncbi/entrez" ) const ( tool = "myapp" email = "user@example.com" ) func main() { // Post UIDs to history server h := entrez.History{} post, err := entrez.DoPost("protein", tool, email, &h, 15718680, 15718681, 15718682, 15718683) if err != nil { log.Fatal(err) } fmt.Printf("Posted UIDs to history server\n") fmt.Printf("WebEnv: %s\n", h.WebEnv) fmt.Printf("QueryKey: %d\n", h.QueryKey) // Now use the history to fetch all posted records params := &entrez.Parameters{ RetType: "fasta", RetMode: "text", } reader, err := entrez.Fetch("protein", params, tool, email, &h) if err != nil { log.Fatal(err) } defer reader.Close() _ = post // Post result can be used for error checking } ``` -------------------------------- ### Perform BLAST Search Source: https://github.com/biogo/ncbi/blob/master/README.md Submits a query to the BLAST server, handles retries, and retrieves results. Ensure the 'tool' constant is correctly set for the BLAST server. The function respects request frequency policies. ```go // tool is required by the BLAST server. const tool = "blast.example" // BLAST submits a query to the BLAST server, waits for the server's estimated time of // execution and retrieves the search status. If the search is ready the results are then // retrieved and returned. If errors are returned during data retrieval from the server, // retrieval is retried with up to retry attempts; all server requests honour the request // frequency policy specified in the BLAST usage guidelines. func BLAST(query string, retry int, pp *blast.PutParameters, gp *blast.GetParameters, email string) (*blast.Output, error) { // Put the query request to the BLAST server. r, err := blast.Put(query, pp, tool, email) if err != nil { return nil, err } var o *blast.Output for k := 0; k < retry; k++ { // Wait for RTOE to elapse and get search status. var s *blast.SearchInfo s, err = r.SearchInfo(tool, email) if err != nil { return nil, err } // Output search status. fmt.Println(s) switch s.Status { case "WAITING": continue case "FAILED": return nil, fmt.Errorf("search: %s failed", r) case "UNKNOWN": return nil, fmt.Errorf("search: %s expired", r) case "READY": if !s.HaveHits { return nil, fmt.Errorf("search: %s no hits", r) } default: return nil, errors.New("unknown error") } // We have hits, so get the BLAST output. o, err = r.GetOutput(gp, tool, email) if err == nil { return o, err } } return nil, fmt.Errorf("%s exceeded retries", r) } ``` -------------------------------- ### Retrieve Records with entrez.Fetch Source: https://context7.com/biogo/ncbi/llms.txt Fetches full records from Entrez databases by UID or history server. Returns an io.ReadCloser for streaming. ```go package main import ( "bytes" "fmt" "io" "log" "github.com/biogo/ncbi" "github.com/biogo/ncbi/entrez" ) const ( tool = "myapp" email = "user@example.com" ) func main() { ncbi.SetTimeout(0) // Disable timeout for large fetches // Fetch specific protein sequences by UID in FASTA format params := &entrez.Parameters{ RetType: "fasta", RetMode: "text", } reader, err := entrez.Fetch("protein", params, tool, email, nil, 15718680, 15718681) if err != nil { log.Fatal(err) } defer reader.Close() buf := new(bytes.Buffer) _, err = io.Copy(buf, reader) if err != nil { log.Fatal(err) } fmt.Println(buf.String()) // Fetch from history server (for large result sets) h := entrez.History{} search, err := entrez.DoSearch("nucleotide", "rbcL[gene] AND plants[organism]", nil, &h, tool, email) if err != nil { log.Fatal(err) } fmt.Printf("Found %d nucleotide records\n", search.Count) // Fetch in batches using history batchParams := &entrez.Parameters{ RetType: "gb", // GenBank format RetMode: "text", RetMax: 100, RetStart: 0, } reader2, err := entrez.Fetch("nucleotide", batchParams, tool, email, &h) if err != nil { log.Fatal(err) } defer reader2.Close() data, _ := io.ReadAll(reader2) fmt.Printf("Retrieved %d bytes of GenBank data\n", len(data)) } ``` -------------------------------- ### Entrez DoGlobal - Search Across All Databases Source: https://context7.com/biogo/ncbi/llms.txt Searches for a query term across all Entrez databases and returns the count of matching records for each database. Requires tool name and email for identification. ```go package main import ( "fmt" "log" "github.com/biogo/ncbi/entrez" ) const ( tool = "myapp" email = "user@example.com" ) func main() { // Search for "BRCA1" across all NCBI databases global, err := entrez.DoGlobal("BRCA1", tool, email) if err != nil { log.Fatal(err) } fmt.Printf("Global search results for 'BRCA1':\n") for _, result := range global.Results { if result.Count > 0 { fmt.Printf(" %s: %d records\n", result.DbName, result.Count) } } } ``` -------------------------------- ### BLAST Put - Submit BLAST Query Source: https://context7.com/biogo/ncbi/llms.txt Submits a nucleotide or protein sequence to the NCBI BLAST server for analysis. Returns a request ID (RID) for tracking the job. Requires tool name and email. ```go package main import ( "fmt" "log" "github.com/biogo/ncbi/blast" ) const ( tool = "myapp" email = "user@example.com" ) func main() { // FASTA sequence to search query := `>test_sequence ATGCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCG ATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGA` // Configure BLAST parameters params := &blast.PutParameters{ Program: "blastn", // nucleotide BLAST Database: "nt", // nucleotide collection HitListSize: 50, // max hits to return Megablast: true, // use Megablast for faster search } // Submit the query rid, err := blast.Put(query, params, tool, email) if err != nil { log.Fatal(err) } fmt.Printf("BLAST job submitted!\n") fmt.Printf("Request ID (RID): %s\n", rid) fmt.Printf("Estimated time: %v\n", rid.TimeOfExecution()) } ``` -------------------------------- ### Configure HTTP Client Timeout Source: https://context7.com/biogo/ncbi/llms.txt Sets the timeout duration for HTTP requests to NCBI services. The default timeout is 10 seconds. Setting the timeout to 0 disables it. ```APIDOC ## ncbi.SetTimeout - Configure HTTP Client Timeout ### Description Sets the timeout duration for HTTP requests to NCBI services. The default timeout is 10 seconds. ### Method func SetTimeout(timeout time.Duration) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "time" "github.com/biogo/ncbi" ) func main() { // Disable timeout for large downloads ncbi.SetTimeout(0) // Or set a custom timeout of 30 seconds ncbi.SetTimeout(30 * time.Second) } ``` ### Response None (This is a configuration function) ### Error Handling None ``` -------------------------------- ### Search Entrez Databases Source: https://context7.com/biogo/ncbi/llms.txt Executes a search query against an Entrez database. Supports history tracking via the History struct and custom search parameters. ```go package main import ( "fmt" "log" "github.com/biogo/ncbi/entrez" ) const ( tool = "myapp" email = "user@example.com" ) func main() { // Search for human insulin protein sequences h := entrez.History{} search, err := entrez.DoSearch("protein", "insulin[protein name] AND human[organism]", nil, &h, tool, email) if err != nil { log.Fatal(err) } fmt.Printf("Found %d records\n", search.Count) fmt.Printf("Returned %d IDs (RetMax: %d)\n", len(search.IdList), search.RetMax) fmt.Printf("WebEnv: %s\n", h.WebEnv) fmt.Printf("QueryKey: %d\n", h.QueryKey) // Print first 10 UIDs for i, id := range search.IdList { if i >= 10 { break } fmt.Printf(" UID: %d\n", id) } // Search with parameters params := &entrez.Parameters{ RetMax: 100, Sort: "relevance", DateType: "pdat", MinDate: "2020/01/01", MaxDate: "2023/12/31", } search2, err := entrez.DoSearch("pubmed", "CRISPR gene editing", params, nil, tool, email) if err != nil { log.Fatal(err) } fmt.Printf("\nPubMed search found %d articles\n", search2.Count) } ``` -------------------------------- ### Create Rate Limiter Source: https://context7.com/biogo/ncbi/llms.txt Creates a thread-safe rate limiter to control request frequency. This is used internally by the library but can also be used for custom request scheduling. ```APIDOC ## ncbi.NewLimiter - Create Rate Limiter ### Description Creates a thread-safe rate limiter to control request frequency. Used internally by the library but can be used for custom request scheduling. ### Method func NewLimiter(interval time.Duration) *Limiter ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "time" "github.com/biogo/ncbi" ) func main() { // Create a limiter that allows one request per second limiter := ncbi.NewLimiter(time.Second) for i := 0; i < 5; i++ { limiter.Wait() // Blocks until safe to proceed fmt.Printf("Request %d at %v\n", i, time.Now()) } } ``` ### Response - **Limiter** (*Limiter) - A pointer to a new rate limiter. ### Error Handling None ``` -------------------------------- ### POST /blast/ - Submit BLAST Query Source: https://context7.com/biogo/ncbi/llms.txt Submits a new BLAST query to the NCBI server and returns a RID (Request ID) for tracking the job. The query sequence and parameters for the BLAST search are provided in the request. ```APIDOC ## POST /blast/ ### Description Submits a new BLAST query to the NCBI server and returns a RID (Request ID) for tracking the job. The query sequence and parameters for the BLAST search are provided in the request. ### Method POST ### Endpoint /blast/ ### Parameters #### Query Parameters - **tool** (string) - Required - User identification string. - **email** (string) - Required - User's email address. #### Request Body - **query** (string) - Required - The query sequence in FASTA format. - **putParams** (object) - Optional - Parameters for the BLAST submission. - **Program** (string) - Required - The BLAST program to use (e.g., "blastp"). - **Database** (string) - Required - The database to search against (e.g., "swissprot"). - **HitListSize** (integer) - Optional - The maximum number of hits to return. ### Request Example ```json { "query": ">test\nMKTAYIAKQRQISFVKSHFSRQLEEALLYTI", "putParams": { "Program": "blastp", "Database": "swissprot", "HitListSize": 10 } } ``` ### Response #### Success Response (200) - **rid** (string) - The Request ID for the submitted job. #### Response Example ```json { "rid": "ABC123XYZ789" } ``` ``` -------------------------------- ### POST /blast/rid - Create RID from Existing ID Source: https://context7.com/biogo/ncbi/llms.txt Creates a new RID object from a previously obtained request ID string. This is useful for retrieving results from searches submitted earlier without resubmitting the query. ```APIDOC ## POST /blast/{rid} ### Description Creates a new RID object from a previously obtained request ID string. This is useful for retrieving results from searches submitted earlier without resubmitting the query. ### Method POST ### Endpoint /blast/{rid} ### Parameters #### Path Parameters - **rid** (string) - Required - The existing Request ID string. #### Query Parameters - **tool** (string) - Required - User identification string. - **email** (string) - Required - User's email address. ### Response #### Success Response (200) - **message** (string) - Confirmation that the RID object was created. #### Response Example ```json { "message": "RID object created successfully" } ``` ``` -------------------------------- ### entrez.DoSearch - Search Entrez Databases Source: https://context7.com/biogo/ncbi/llms.txt Searches an Entrez database with a text query and returns matching UIDs. It supports using the Entrez history server. ```APIDOC ## entrez.DoSearch - Search Entrez Databases ### Description Searches an Entrez database with a text query and returns matching UIDs (unique identifiers). Supports the Entrez history server for storing search results for later retrieval. ### Method func DoSearch(db, query string, params *Parameters, history *History, tool, email string) (*SearchResult, error) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "log" "github.com/biogo/ncbi/entrez" ) const ( tool = "myapp" email = "user@example.com" ) func main() { // Search for human insulin protein sequences h := entrez.History{} search, err := entrez.DoSearch("protein", "insulin[protein name] AND human[organism]", nil, &h, tool, email) if err != nil { log.Fatal(err) } fmt.Printf("Found %d records\n", search.Count) fmt.Printf("Returned %d IDs (RetMax: %d)\n", len(search.IdList), search.RetMax) fmt.Printf("WebEnv: %s\n", h.WebEnv) fmt.Printf("QueryKey: %d\n", h.QueryKey) // Print first 10 UIDs for i, id := range search.IdList { if i >= 10 { break } fmt.Printf(" UID: %d\n", id) } // Search with parameters params := &entrez.Parameters{ RetMax: 100, Sort: "relevance", DateType: "pdat", MinDate: "2020/01/01", MaxDate: "2023/12/31", } search2, err := entrez.DoSearch("pubmed", "CRISPR gene editing", params, nil, tool, email) if err != nil { log.Fatal(err) } fmt.Printf("\nPubMed search found %d articles\n", search2.Count) } ``` ### Response #### Success Response (200) - **Count** (int) - The total number of records matching the query. - **RetMax** (int) - The maximum number of records to return. - **IdList** ([]int) - A list of UIDs for the matching records. - **History** (*History) - If provided, this struct will be populated with WebEnv and QueryKey for history server usage. - **History.WebEnv** (string) - The Web Environment identifier. - **History.QueryKey** (int) - The Query Key identifier. #### Response Example ```json { "Count": 500, "RetMax": 20, "IdList": [12345, 67890, ...], "History": { "WebEnv": "some_web_env_string", "QueryKey": 1 } } ``` ### Error Handling - **error** - An error object if the request fails. ``` -------------------------------- ### Entrez DoCitMatch - Match Citations to PubMed IDs Source: https://context7.com/biogo/ncbi/llms.txt Matches provided journal citation details to their corresponding PubMed IDs. Requires tool name and email for identification. Input is a map of citation queries. ```go package main import ( "fmt" "log" "github.com/biogo/ncbi/entrez" ) const ( tool = "myapp" email = "user@example.com" ) func main() { // Match citations to PubMed IDs citations := map[string]entrez.CitQuery{ "citation1": { JournalTitle: "Proc Natl Acad Sci U S A", Year: "1991", Volume: "88", FirstPage: "2297", AuthorName: "Sanger F", }, "citation2": { JournalTitle: "Nature", Year: "2003", Volume: "422", FirstPage: "835", }, } results, err := entrez.DoCitMatch(citations, tool, email) if err != nil { log.Fatal(err) } for key, pmid := range results { fmt.Printf("%s -> PMID: %d\n", key, pmid) } } ``` -------------------------------- ### BLAST Rid.SearchInfo - Check BLAST Job Status Source: https://context7.com/biogo/ncbi/llms.txt Polls the NCBI BLAST server to check the status of a submitted job using its RID. It automatically respects rate limits and continues polling until the job is READY, FAILED, or UNKNOWN. Requires tool name and email. ```go package main import ( "fmt" "log" "github.com/biogo/ncbi/blast" ) const ( tool = "myapp" email = "user@example.com" ) func main() { query := ">seq1\nMKTAYIAKQRQISFVKSHFSRQLE" params := &blast.PutParameters{ Program: "blastp", Database: "nr", } rid, err := blast.Put(query, params, tool, email) if err != nil { log.Fatal(err) } fmt.Printf("RID: %s\n", rid) // Poll for status (respects rate limits automatically) for { info, err := rid.SearchInfo(tool, email) if err != nil { log.Fatal(err) } fmt.Printf("Status: %s, Has Hits: %v\n", info.Status, info.HaveHits) switch info.Status { case "WAITING": fmt.Println("Still processing, waiting...") continue case "FAILED": log.Fatal("BLAST search failed") case "UNKNOWN": log.Fatal("BLAST search expired or unknown RID") case "READY": if info.HaveHits { fmt.Println("Search complete with hits!") } else { fmt.Println("Search complete, no hits found") } return } } } ``` -------------------------------- ### Find Related Records with entrez.DoLink Source: https://context7.com/biogo/ncbi/llms.txt Finds UIDs that are linked to a set of input UIDs in the same or different Entrez database. ```go package main import ( "fmt" "log" "github.com/biogo/ncbi/entrez" ) const ( tool = "myapp" email = "user@example.com" ) func main() { // Find nucleotide sequences linked to protein UIDs proteinUIDs := []int{15718680, 15718681} link, err := entrez.DoLink("protein", "nuccore", "", "", nil, tool, email, nil, proteinUIDs) if err != nil { log.Fatal(err) } for _, linkSet := range link.LinkSets { fmt.Printf("From database: %s\n", linkSet.DbFrom) fmt.Printf("Input IDs: %v\n", linkSet.IdList) for _, linkDb := range linkSet.LinkSetDbs { fmt.Printf(" Linked to %s via %s:\n", linkDb.DbTo, linkDb.LinkName) for _, l := range linkDb.Links { fmt.Printf(" UID: %d (Score: %d)\n", l.Id.Id, l.Score) } } } // Find PubMed articles related to a gene geneUIDs := []int{672} // BRCA1 gene pubmedLinks, err := entrez.DoLink("gene", "pubmed", "", "", nil, tool, email, nil, geneUIDs) if err != nil { log.Fatal(err) } fmt.Printf("\nFound links to PubMed for gene 672\n") for _, ls := range pubmedLinks.LinkSets { for _, ldb := range ls.LinkSetDbs { fmt.Printf(" %s: %d linked articles\n", ldb.LinkName, len(ldb.Links)) } } } ```