How to use the Bleve library for full-text search in Golang
Bleve is a lightweight, embeddable full-text search library for Go that enables efficient indexing and querying without external dependencies. First, install it via go get github.com/blevesearch/bleve/v2. Then create a disk-based index using bleve.New("example.bleve", mapping), where mapping := bleve.NewIndexMapping() defines text analysis rules. Index structured data like structs or maps by calling index.Index("id", doc)—for example, a Product struct with name, description, and price. Search with queries such as bleve.NewMatchQuery("laptop"), wrapped in a bleve.NewSearchRequest(), then execute against the index to retrieve results with IDs and scores. Update documents by reindexing with the same ID; delete using index.Delete("id"). Customize indexing behavior by defining field-specific mappings, controlling analyzers, or disabling indexing on certain fields. Close the index with index.Close() and reopen later via bleve.Open("example.bleve"). While not as powerful as Elasticsearch, Bleve excels in simplicity and performance for small to medium-scale applications requiring embedded search.

Bleve is a powerful full-text search library for Go that allows you to index and query data efficiently. It’s ideal for adding search capabilities directly into your Go applications without relying on external services like Elasticsearch or Solr. Here's how to get started using Bleve in Golang.
Install Bleve
To begin, install the Bleve library using Go modules:
go get github.com/blevesearch/bleve/v2This command adds Bleve as a dependency to your project.
Create an Index
Bleve stores searchable data in an index. You can create an in-memory or persistent index on disk. Below is an example of creating a basic disk-based index:
mapping := bleve.NewIndexMapping()
index, err := bleve.New("example.bleve", mapping)
if err != nil {
log.Fatal(err)
}
The NewIndexMapping() function sets up how Bleve analyzes and indexes text. The default mapping works well for general use.
Index Some Data
Once the index is created, you can add documents. A document can be a struct, map, or any JSON-marshalable type. For example:
type Product struct {Name string `json:"name"`
Desc string `json:"desc"`
Price float64 `json:"price"`
}
doc := Product{
Name: "Laptop",
Desc: "A high-performance laptop with SSD",
Price: 999.99,
}
index.Index("id1", doc)
The first argument to Index() is a unique ID for the document.
Search the Index
To perform a search, create a query and execute it against the index. Here's how to do a simple keyword search:
query := bleve.NewMatchQuery("laptop")search := bleve.NewSearchRequest(query)
result, err := index.Search(search)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found %d results\n", result.Total)
for _, hit := range result.Hits {
fmt.Printf("ID: %s, Score: %f\n", hit.ID, hit.Score)
}
The MatchQuery looks for documents where any indexed field contains the term "laptop". You can also use more specific queries like NewMatchPhraseQuery or NewTermQuery for exact matches.
Update or Delete Documents
To update a document, simply call Index() again with the same ID. Bleve will replace the existing document.
To delete a document, use:
index.Delete("id1")Customize Index Mapping (Optional)
If you need control over how fields are analyzed, define a custom mapping. For example, to disable indexing on a field:
mapping := bleve.NewIndexMapping()err := mapping.AddDocumentMapping("Product", productMapping)
if err != nil {
log.Fatal(err)
}
You can specify which fields to index, their types, and which analyzers to use (e.g., standard, keyword, etc.).
Close and Reopen Index
When done, close the index:
index.Close()To reopen later:
index, _ = bleve.Open("example.bleve")This loads the previously saved index from disk.
Basically, Bleve gives you a lightweight, embeddable search engine in pure Go. With just a few lines, you can index structured data and run fast, relevant text searches. It's not as feature-rich as large-scale search servers, but it's perfect for small to medium applications where simplicity and low overhead matter.
The above is the detailed content of How to use the Bleve library for full-text search in Golang. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20522
7
13634
4
How to apply the facade pattern (Facade) in Golang Go language simplifies the API of complex systems
Mar 10, 2026 pm 12:27 PM
The Facade should be used when the caller needs to write more than 5 lines of initialization, call more than 3 packages in sequence, and manually handle intermediate states; it should pass the interface rather than the specific type, provide 3 to 5 core methods, and enforce Shutdown() resource cleanup.
SQL performance analysis tool in Golang web development Go language GORM-Query-Logger
Mar 11, 2026 am 11:12 AM
GORM does not print complete SQL by default in order to prevent sensitive data from leaking and reduce log volume. It is necessary to customize the Logger and rewrite the LogMode and Info methods to splice sql.String() and sql.Variables to achieve parameterized output. SlowThreshold only counts the time spent on the GORM layer, and does not include network and database lock waits.
How to implement gRPC server-side streaming mode in Golang. Practical combat of real-time data streaming in Go language
Mar 10, 2026 am 10:21 AM
The server-side stream is a gRPC communication mode with a single request from the client and multiple responses from the server. It is suitable for "single push, multiple receive" scenarios such as real-time push and log pulling. The definition needs to declare rpcGetMetrics(MetricsRequest)returns(streamMetricsResponse) in .proto. The server-side implementation must call stream.Send() multiple times and avoid reusing the same instance. The client must loop Recv() and correctly handle io.EOF.
How to parse and generate CSV files in Golang Go language encoding/csv standard library tips
Mar 10, 2026 am 11:39 AM
csv.Reader defaults to ErrFieldCount instead of panic if the number of fields is inconsistent, but ignoring errors will cause subsequent panic; to tolerate fluctuations, FieldsPerRecord=-1 must be set; csv.Encoder does not handle encoding, and Chinese needs to be manually transcoded or add UTF-8BOM; ReadAll is prone to OOM, and loop Read should be used instead; configurations such as custom delimiters must be set before reading and writing for the first time.
How to implement microservice configuration center hot update in Golang Go language Apollo configuration integration
Mar 10, 2026 am 10:52 AM
ApolloClient.GetConfig() cannot get the updated value because it does not monitor changes by default. You need to explicitly enable long polling (WithLongPolling(true)) and register the AddChangeListener callback. In the callback, deserialize the new configuration and use the atomic pointer to switch instances.
How to use Dapr to build cloud-native microservices in Golang Go language Dapr SDK Development Guide
Mar 10, 2026 am 11:21 AM
The root cause is that the main goroutine is not blocked. dapr.Run() only registers the component and starts the service but does not block the main thread. You need to wait explicitly with select{} or signal.Notify; the business logic should be passed in as a callback or started in an independent goroutine.
How to configure Golang plug-in in VSCode Go language code completion and debugging environment optimization
Mar 10, 2026 am 11:36 AM
Go plug-in installed but not completed? Check whether gopls actually enables VSCode's Go plug-in (golang.go) which relies on gopls to provide semantic completion, jump and diagnosis by default. However, many people think that everything is fine after installing the plug-in - in fact, gopls may not be running at all. Common error phenomena: Ctrl Space only has basic syntax prompts and no field/method completion; F12 jump fails; no govet or staticcheck error is reported after saving. Open the command panel (Ctrl Shift P), run Go:Install/UpdateTools, check gopls and confirm the installation
How to operate Docker containers through API in Golang. Use of Go language Docker Client SDK
Mar 10, 2026 am 11:33 AM
HostConfig and NetworkingConfig need to be initialized explicitly; ContainerConfig.Image must be filled with the tagged image name; HostConfig.Mounts.Type must be lowercase; port mapping requires the cooperation of ExposedPorts and PortBindings; ContainerCreate returns the ID to indicate successful registration and can be started immediately; the log must be set to Follow=false and received with io.Copy; the exitcode should obtain the StatusCode through ContainerWait.





