Skip to content

Martini Updating Solr Documents

This section explains how to update a document in a Solr index within Martini. We provide two methods for updating documents, each illustrated with an example. These examples demonstrate updating the following document:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
{
    "movieTitle": "Forrest Gump",
    "director": "Robert Zemeckis",
    "cast": [
        "Tom Hanks",
        "Robin Wright",
        "Gary Sinise",
        "Mykelti Williamson",
        "Sally Field"
    ],
    "id": "4fc1a64f-7226-4aad-bf27-5c399e2c453c",
    "_version_": 1617640267263770624
}

Access the Code

The scripts in this guide are available in the examples package. This package also includes other services demonstrating the use of SolrMethods and other Solr functionalities.

Method 1: Using Functions

We recommend using the SolrMethods.writeToIndex(...) for ease of updating documents. For partial updates:

  1. Create a SolrInputDocument object.
  2. Set its id field.
  3. Add fields and values that need modification.
  4. Use writeToIndex to index the document.

For example, to update the director field:

1
2
3
4
5
def document = new SolrInputDocument()
document.setField('id', '4fc1a64f-7226-4aad-bf27-5c399e2c453c')
document.setField('director', [set:'Robert Lee Zemeckis'])

'movie-core'.writeToIndex(null, document)
Why use [set:"$newValue"]?

This approach specifies a Map as the second argument in SolrInputDocument#setField, allowing us to define field modifiers. Here, set replaces the field value. Solr supports other modifiers for different update operations.

For complete document updates:

  1. Create and populate your bean object.
  2. Set its unique key property (e.g., id) for identifying the document.
  3. Populate all relevant fields.
  4. Re-index the object using writeToIndex.

Example for complete update:

1
2
3
4
5
MovieDocument movie = new MovieDocument()
movie.setId('4fc1a64f-7226-4aad-bf27-5c399e2c453c')
movie.setDirector('Robert Lee Zemeckis')

'movie-core'.writeToIndex(null, movie)

After committing, only the director field updates, leaving others unchanged.

Method 2: Using SolrClient

For direct interaction with Solr, use SolrMethods.solr(String) to obtain a SolrClient instance. This method requires familiarity with SolrJ and Groovy.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import org.apache.solr.common.SolrInputDocument

// ...

SolrClient solrClient = SolrMethods.solr(coreName)
SolrInputDocument document = new SolrInputDocument()

document.setField('id', '4fc1a64f-7226-4aad-bf27-5c399e2c453c')
document.setField('director', [set:'Robert Lee Zemeckis'])

solrClient.add(document)

In this method, a SolrInputDocument is populated with the necessary fields and then added to the Solr index.