Last active
March 11, 2018 00:21
-
-
Save rippedspine/ce46534ea7e304836442815f8991d2f6 to your computer and use it in GitHub Desktop.
first solution to update searchkit elastic query on prop change
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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