Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save banhaclong20/41599378387a9b84f70dece7e1a0e8c3 to your computer and use it in GitHub Desktop.
Save banhaclong20/41599378387a9b84f70dece7e1a0e8c3 to your computer and use it in GitHub Desktop.
first solution to update searchkit elastic query on prop change
import React from 'react'
import _set from 'lodash/set'
import _get from 'lodash/get'
const searchkit = new SearchkitManager(`/elastic/materials`, {
withCredentials: true
})
class SearchApp extends SearchkitComponent {
setQueryProcessor (props) {
this.searchkit.setQueryProcessor((queryObject) => {
_set(queryObject,
['query', 'bool', 'filter'],
props.toggled
? [{ term: { templateMaterial: true } }]
: [{ term: { materialClass: 'custom' } }]
)
if (_get(queryObject, ['query', 'bool', 'should', 'length'])) {
_set(queryObject, ['min_score'], 0.1)
}
return queryObject
})
}
componentWillReceiveProps (nextProps) {
if (nextProps.toggled !== this.props.toggled) {
this.setQueryProcessor(nextProps)
this.searchkit.performSearch()
}
}
componentWillMount () {
super.componentWillMount()
this.setQueryProcessor(this.props)
}
render () {
return (<div />)
}
}
const queryBuilder = (queryString, options) => {
if (!queryString) return {}
return _set({}, ['bool', 'should'], [
// fuzziness per word match, allow some misspellings
_set({}, ['match', options.field], {
query: queryString,
operator: 'and',
fuzziness: 2
}),
// exact name match with up to 3 missing/jumbled words
_set({}, ['match_phrase', options.field], {
query: queryString,
slop: 3
}),
// id within querystring search
_set({}, ['match', 'id.search'], {
query: queryString,
fuzziness: 1,
boost: 4
}),
// exact id match, most important
_set({}, ['match', 'id'], {
query: queryString,
fuzziness: 1,
boost: 5
})
])
}
class App extends Component {
constructor (props) {
super(props)
this.state = { toggled: false }
}
toggle () {
this.setState({ toggled: !this.state.toggled })
}
render () {
return (
<div>
<button
className={this.state.toggled ? 'bg-primary' : ''}
onClick={this.toggle.bind(this)}
>
toggle material type
</button>
<SearchkitProvider searchkit={searchkit}>
<SearchApp
toggled={this.state.toggled}
queryBuilder={queryBuilder}
queryOptions={{ field: 'name' }}
/>
</SearchkitProvider>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment